Spring MVC 之 文件上传

  文件上传可以说是项目中最常用的功能。

  Spring MVC 为文件上传提供了直接的支持,Spring MVC 提供了一个文件上传的解析类CommonsMultipartResolver,即插即用(在XML文件装配下),该类依赖了Apache Commons FileUpload技术,所以需要导入commons-fileupload.jarcommons-io.jar两个包。

  上传文件,必须将表单的method设置为post,并将enctype设置为multipart/form-data,浏览器才会把文件二进制数据发给服务器。

MultipartFile

MultipartFile提供了获取上传文件内容、文件名等方法,transferTo()可将文件存储到磁盘中。

  1. String getName():获取表单中文件组件的名字。
  2. String getOriginalFilename():获取上传文件的原名。
  3. String getContentType():获取文件MIME类型,如image/jpeg等。
  4. boolean isEmpty():判断是否有上传文件。
  5. long getSize():获取文件的字节大小,单位 bytes
  6. byte[] getBytes():获取文件数据(字节数组)。
  7. InputStream getInputStream():获取文件流。
  8. void transferTo(File dest):将上传文件保存到一个目标文件中。

示例代码

  1. 上传java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

public class UploadFile {

@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
public String uploadFile(HttpServletRequest request, MultipartFile file) throws IllegalStateException, IOException {

if(!file.isEmpty()) {
//获取存放路径
String imgPath = request.getServletContext().getRealPath("/upload/imgs");
//获取文件名
String fileName = file.getOriginalFilename();

File filePath = new File(imgPath,fileName);

//判断文件路径是否存在,如果不存在则创建
if(!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
//将文件保存到目标文档中
file.transferTo(new File(imgPath + File.separator + fileName));
return "success";

}else {
return "false";
}
}
}

  1. springmvc.xml装配CommonsMultipartResolver类。
1
2
3
4
5
6
7
<!-- 配置Spring MVC文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小,单位为字节(10MB) -->
<property name="maxUploadSize" value="20971520"></property>
<!-- 请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单内容,默认为iso-8859-1 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>

对象接收文件

  1. 在实体类文件定义MultipartFile类型的属性,如下:
1
private MultipartFile headImage;// 头象
  1. Controller方法使用对象来接收文带有上传文件的from表单提交的数据。
作者

光星

发布于

2018-02-28

更新于

2022-06-17

许可协议

评论