文件上传是web项目开发中经常用到的功能,例如:用户头像。
文件上传对表单的要求:
① method=”POST”
② enctype=”multipart/form-data”
③ 表单中需要添加文件表单项:<input type=”file” name=”xxx”/>
一旦设置了enctype=”multipart/form-data”,浏览器会采用二进制流的方式来处理表单数据。
Servlet3.0规范已经提供了方法来处理上传文件,但这种上传需要在Servlet中完成,SpringMVC则为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。SpringMVC使用Apache Commons FileUpload组件实现了一个MultipartResolver实现类:CommonsMultipartResolver,因此SpringMVC的文件上传还需要依赖ApacheCommons FileUpload的组件。
Eg:SpringMVC的文件上传:
1. 文件上传页面uploadForm.jsp:
<body>
<h2>测试文件上传...</h2>
<%--上传文件,enctype必须为multipart/form-data,method必须为post --%>
<form action="upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>选择文件</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td>文件描述:</td>
<td><input type="text" name="description"/></td>
</tr>
<tr>
<td><input type="submit" value="上传"/></td>
</tr>
</table>
</form>
</body>
2. FileUploadController:
//动态跳转页面
@RequestMapping(value = "/{formName}")
public String first(@PathVariable String formName) {
return formName;
}
//文件上传
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(HttpServletRequest request, String description,
MultipartFile file) throws Exception {
System.out.println("文件描述:" + description);
//如果文件不为空,写入上传路径
if (!file.isEmpty()) {
//上传文件路径
String path = request.getSession().getServletContext()
.getRealPath("/images/");
//上传文件名:
String fileName = file.getOriginalFilename();//获取上传文件的原始文件名
File filePath = new File(path, fileName);
//判断路径是否存在,如果不存在就创建
if (!filePath.exists()) {
filePath.getParentFile().mkdirs();
}
//将上传的文件保存到一个目标文件
file.transferTo(new File(path + File.separator + fileName));
return "success";
} else {
return "error";
}
}
SpringMVC会将上传的文件绑定到MultipartFile对象中,MultipartFile提供了如下几个常用方法(可参照SpringMVC的API帮助文档):
- byte[] getBytes()
Return the contents of the file as an array of bytes.
- String getContentType()
Return the content type of the file.
- InputStream getInputStream()
Return an InputStream to read the contents ofthe file from.
- String getName()
Return the name of the parameter in themultipart form.
- String getOriginalFilename()
Return the original filename in the client'sfilesystem.
- long getSize()
Return the size of the file in bytes.
- boolean isEmpty()
Return whether the uploaded file is empty,that is, either no file has been chosen in the multipart form or the chosenfile has no content.
- void transferTo(File dest
Transfer the received file to the givendestination file.
3. SringMVC配置文件(springmvc.xml)的配置:
<!-- 配置文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限,单位为字节(10MB) -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取 -->
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
4. 结果:
在浏览器中输入:http://localhost:8080/SpringMVC_fileUpload/uploadForm
会看到磁盘中确实出现了上传的图片: