SpringMVC文件上传下载

本文详细介绍了如何使用SpringMVC(SSM框架的一部分)实现文件上传和下载功能,包括配置web.xml、springmvc.xml,以及编写Controller层代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:有关jar

 

2、web.xml标配

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="WebApp_ID" version="2.5">

<display-name>SSM-1</display-name>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<!-- 1、将Spring配置加入到web项目中 -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

<!-- 监听器 -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<!-- Spring MVC配置 -->

<!-- 配置springmvc 的DispatcherServlet -->

<!--配置DispatcherServlet -->

<servlet>

<servlet-name>DispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:springmvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>DispatcherServlet</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>
<!-- 过滤器,统一编码:UTF-8 -->

<filter>

<filter-name>CharacterEncodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>CharacterEncodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

</web-app>

 

 

 

 

3、springmvc.xml配置(注意这是SSM的配置,如果单纯是SpringMVC就要把Spring注释掉):

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context.xsd

    http://www.springframework.org/schema/mvc

    https://www.springframework.org/schema/mvc/spring-mvc.xsd">



<!-- 1.开启SpringMVC注解驱动         -->

   <mvc:annotation-driven/>

   <!-- 2、开启静态资源默认Servlet配置 -->

<mvc:default-servlet-handler/>

<!-- 设置/scripts/为 静态资源 -->

<mvc:resources location="/scripts/" mapping="/scripts/**"/>

   

   <!-- 2.扫描web相关的bean -->

   <context:component-scan base-package="com.ssm"/>



<!-- 3、配置视图解析器         -->

<!-- 配置视图解析器,将控制器方法返回的逻辑视图转化为物理视图 -->

<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<!-- <property name="prefix" value="/ch06/"></property> -->

<property name="prefix" value="/ch10/"></property>

<property name="suffix" value=".jsp"></property>

</bean>  

 



<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">

<property name="order" value="50"></property>

</bean>





<!-- 配置文件上传下载 -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- 设置上传的最大尺度1MB -->

<property name="maxUploadSize" value="1048576"></property>

<!-- 字符编码 -->

<property name="defaultEncoding" value="UTF-8"></property>

</bean>        



</beans>

4、编写Demo

Controller层编写:(用就直接复制,然后进行修改,当然必须每个过程清清楚楚)

package com.ssm.controller;



import java.io.File;

import java.util.List;

import java.util.UUID;



import javax.servlet.http.HttpServletRequest;



import org.apache.commons.io.FileUtils;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;



@Controller

public class FileUploadController {

@RequestMapping(value = "/fileUpload")

public String fileUpload(@RequestParam(value = "file",required = false) MultipartFile file,

HttpServletRequest request,ModelMap model) {

//服务器端upload文件夹物理路径

//1. 获取上传的目录路径

        // D:/classes/IdeaProjects2019/springmvc02/target/springmvc02-1.0-SNAPSHOT/upload

String path=request.getSession().getServletContext().getRealPath("/upload");

System.out.println(path);

//获取文件名

String fileName=file.getOriginalFilename();

//实例化一个File对象,表示目标文件(包含物理路径). 创建目录

File targetFile=new File(path,fileName);



if(!targetFile.exists())

{

targetFile.mkdirs();

System.out.println("创建目录:"+targetFile);

}

try {

//将上传文件写到服务器上指定的文件

file.transferTo(targetFile);

} catch (Exception e) {

e.printStackTrace();

}

model.put("fileUrl", request.getContextPath()+"/upload/"+fileName);



//将文件放到request域

model.put("fileName", fileName);



return "success";

}



@RequestMapping(value = "/upload")

public String upload(@RequestParam("description")String description,

@RequestParam(value = "files",required = false) List<MultipartFile> files,

HttpServletRequest request,ModelMap model) {

//判断文件上传是否存在

if(!files.isEmpty()&&files.size()>0)

{

//循环输出上传的文件

for (MultipartFile file : files) {

//获取上传文件的原名称

String originalFilename=file.getOriginalFilename();

//获取上传文件的保存地址目录

String dirPath=request.getSession().getServletContext().getRealPath("/upload");

File filePath=new File(dirPath);

if(!filePath.exists()) {

filePath.mkdirs();

System.out.println(filePath);

}



String newFileName=description+"-"+UUID.randomUUID()+"-"+originalFilename;

try {

file.transferTo(new File(dirPath,newFileName));



} catch (Exception e) {

e.printStackTrace();

return "error";



}

}

return "success";

}

return "error";

}



@RequestMapping("/fileDownload")

public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,

@RequestParam("fileName") String fileName, Model model) throws Exception{



//下载路径

String path=request.getServletContext().getRealPath("/upload/");

//创建文件对象

File file=new File(path+File.separator+fileName);

//设置响应头、

HttpHeaders headers=new HttpHeaders();

//下载显示的文件名,解决中文乱码问题

String downloadFileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");

//通知浏览器,下载方式(attactment)打开文件

headers.setContentDispositionFormData("attactment", downloadFileName);

//定义二进制流的方式下载文件数据

headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);



}



}

Index.jsp------------------------------------------------------------------------------------------------------------------


 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>



<form action="../fileUpload" enctype="multipart/form-data" method="post">

              选择文件<input type="file" name="file"><br><br>

                      <input type="submit" value="上传">

     </form>

</body>

</html>

fileUpload.jsp(多文件上传)------------------------------------------------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>



<form action="../upload" enctype="multipart/form-data" method="post">

             文件描述:<input type="text" name="description"><br><br> 

              选择文件<input type="file" name="files" multiple="multiple"><br><br>

                      <input type="submit" value="上传">

     </form>

</body>

</html>

 

Success.jsp-----------------------------------------------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

文件上传成功!<br>

上传文件的路径:${requestScope.fileUrl}<br>



<a href="fileDownload?fileName=${requestScope.fileName}">${requestScope.fileName}</a>



</body>

</html>

 

error.jsp-----------------------------------------------------------------------------------------------------------------


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

文件上传失败,请重新上传!<br>

</body>

</html>

结果演示:

点击下面的蓝色是下载,当然还有多文件上传就不演示了,自己看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值