出版圈郭志敏 2018-03-30
Spring MVC文件上传
1 文件上传是项目开发当中最常用的功能。为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这种情况下,浏览器才会把用户选择的文件二进制数据发送给服务器。
2 一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的HTTP响应。Spring MVC使用Apache Commons FileUpload 技术实现了一个MultiPartResolver实现类:CommonsMultipartResolver.因此,Spring MVC的文件上传还需要Apache CommonsFileUpload 的组件。
Spring MVC的文件上传:程序清单:codes/07/FileUploadTest/WebContent/WEB-INF/content/uploadForm.jsp
<html> <head> <title>文件上传</title> </head> <body> <h2>文件上传</h2> <form action="upload" enctype="multipart/form-data" method="post"> <table> <tr> <td>文件描述</td> <td><input type="text" name="description"></td> </tr> <tr> <td>请选择文件:</td> <td><input type="file" name="file"></td> </tr> <tr> <td><input type="submit" value="上传"></td> </tr> </table> </form> </body> </html><br />
负责上传文件的表单和一般表单有一些区别,负责上传文件的表单的编码类型必须是“multipart/form-data”.
Spring MVC会将上传文件绑定大盘MultipartFile对象中。MultipartFile提供了获取上传文件内容、文件名等方法。通过transferTo()方法还可以将文件存储到硬件中,MultipartFile对象中的常用方法如下;
程序清单:codes/07/FileUploadTest/src/org/fkit/controller/FileUploadController
//上传文件会自动绑定到MultipartFile中
@RequestMapping(value="/upload",method=RequestMethod.Post)
public String upload(HttpServletRequest request,
@RequestParam("description") String description,
@RequestParam("file") MultiparFile file ) throws Exception{
System.out.println(description);
//如果文件不为空,写入上传路径
if(!file.isEmpty()){
//上传文件路径
String path = request.getServletContext().getRealPath("/images/");
//上传文件名
String filename = file.getOriginalFilename();
File filename = new File(path,filename);
//判断路径是否存在,如果不存在就创建一个
if(!filepath.getParentFile().exists()){
filepath.getParentFile().mkdir();
}
//将上传文件保存到一个目标文件当中
file.transferTo(new File(path+File.separator+filename));
return "success";
} else{
return "error";
}
}Spring MVC上下文中默认没有装备MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver.
程序清单:codes/07/FileUploadTest/WebContent/WEB-INF/springmvc-config.xml
<bean
id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传文件大小上限,单位为字节(10MB)-->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!--请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1-->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>需要注意的是,CommonsMultipartResolver必须依赖于Apache Commons FileUpload 的组件,所以需要将Apache 的Commons FileUpload的jar包放到项目的类路径下。
部署FileUploadTest这个Web应用,在浏览器中输入如下URL来测试应用:
http://localhost:8080/FileUploadTest/uploadForm
然后输入文件描述信息并选择上传文件。单击上传按钮,文件就会被上传并保存到项目的images文件夹下面。