spring mvc 是目前最优秀的 java web 领域的 mvc 框架,本文介绍 spring mvc 中如何进行文件上传。看到很多人使用了 spring mvc,但是确自己通过流的方式上传文件,其实 spring mvc 为我们内建了若干文件上传模块,使用起来十分简单,并且性能优越,因此既然使用了 spring mvc,就推荐使用这种方式进行文件上传。下面介绍如何使用 spring mvc 内建的文件上传模块。
1.加入 commons-fileupload 依赖
spring mvc的文件上传模块底层依赖 apache 的 commons-fileupload文件上传组件
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2.表单指定enctype
不要忘了指定 form 的 enctype 属性为multipart/form-data
<form method="post" action="/form" enctype="multipart/form-data"> <input type="file" name="file"/> <form>
3.配置 spring mvc 文件上传的解析器
spring mvc的文件上传模块是可插拔的,默认没有启用,只要在 spring mvc 容器中实例化 MultipartResolver 接口的实现类即可,spring mvc 为我们提供了整合了 commons-fileupload 的 CommonsMultipartResolver 解析器,只需实例化该类即可
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大文件大小,单位字节 --> <property name="maxUploadSize" value="100000"/> </bean>
注意:博主在这里遇到一个大坑,就是这个解析器id必须是multipartResolver,否则spring将在上传超过3m文件时会报错!!!
4.使用MultipartFile类的相关API完成文件上传
@Controller public class FileUploadController { private static final String UPLOAD_DIR = "/srv/www/upload/"; private static final long MAX_FILE_SISE = 1000000; @RequestMapping("/upload") public void uploadFile(@RequestParam("file") MultipartFile file) { if(!file.isEmpty()) { //获取文件类型 String contentType = file.getContentType(); if(!contentType.equals("")) { //可以对文件类型进行检查 } //获取input域的name属性 String name = file.getName(); //获取文件名,带扩展名 String originFileName = file.getOriginalFilename(); //获取文件扩展名 String extension = originFileName.substring(originFileName.lastIndexOf(".")); System.out.println(extension); //获取文件大小,单位字节 long site = file.getSize(); if(site > MAX_FILE_SISE) { //可以对文件大小进行检查 } //构造文件上传后的文件绝对路径,这里取系统时间戳+文件名作为文件名 //不推荐这么写,这里只是举例子,这么写会有并发问题 //应该采用一定的算法生成独一无二的的文件名 String fileName = UPLOAD_DIR + String.valueOf(System.currentTimeMillis()) + extension; try { file.transferTo(new File(fileName)); } catch (Exception e) { e.printStackTrace(); } } } }