Fork me on GitHub

SpringMVC学习6-文件上传

Spring MVC

SpringMVC是基于MVC思想的JAVA WEB实现框架,是Spring家族的一员,它基于前置控制器来接收并分发请求,支持参考验证、请求参数封装、拦截、Restful等功能,是目前较为流行的MVC框架

本系列学习笔记包含如下的课程内容:

  • MVC思想
  • Hello案例
  • 请求和响应处理
  • 文件上传和下载处理
  • 参数验证
  • 请求拦截
  • RESTful风格
  • 日志

File Upload

文件上传是 Web 应用的常见功能用例,SpringMVC 提供 MultipartResolver 接口来处理。

配置 pom.xml

1
2
3
4
5
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>

MultipartResolver

A strategy interface for multipart file upload resolution.
There is no default resolver implementation used for Spring DispatcherServlets, to define an implementation, create a bean with the id “multipartResolver” in a DispatcherServlet’s application context, like org.springframework.web.multipart.commons.CommonsMultipartResolver for Jakarta Commons FileUpload.

配置 MultipartResolver 实现类

在配置信息类中声明一个方法,来提供 MultipartResolver 实现类,注意方法名就是默认 bean id.

1
2
3
4
5
6
7
8
9
10
/**
* MultipartResolver
*/
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setDefaultEncoding("UTF-8");
multipartResolver.setMaxUploadSize(20 * 1024 * 1024); //20MB
return multipartResolver;
}

当然,如果你采用xml配置,在xml中配置一个叫 multipartResolver的Bean即可.

Form 表单

写一个 form 表单来提交需要上传的文件

1
2
3
4
5
<form method="post" action="${path}/request/demo4" enctype="multipart/form-data">
文件:<input type="file" name="myFile">
<br/>
<input type="submit" value="上传文件">
</form>

注意:

  • input type="file"
  • enctype 必须声明为 multipart/form-data,否则仅会上传文件名字符串

控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RequestMapping(value = "/demo4", method = RequestMethod.POST)
public String demo4(@RequestParam MultipartFile myFile,
Model model,
HttpSession session) throws IOException {
//获得原来文件名(含后缀名)
String originalFilename = myFile.getOriginalFilename();
int pos = originalFilename.lastIndexOf(".");
//原文件后缀名
String suffix = originalFilename.substring(pos);
//保存文件
ServletContext application = session.getServletContext();
String realPath = application.getRealPath("uploadFiles");
//产生一个uuid随机文件名
String uuid = UUID.randomUUID().toString();
String fullPath = realPath + File.separator + uuid + suffix;
System.out.println("fullPath:" + fullPath);
FileUtils.copyInputStreamToFile(myFile.getInputStream(), new File(fullPath));
model.addAttribute("originalFilename", originalFilename);
model.addAttribute("fullPath", fullPath);
return "result4";
}
  • MultipartFile: 用来接收和封装上传的文件
  • application.getRealPath():获得运行期项目根目录
  • org.apache.commons.io.FileUtils: 提供了方便的 io 方法