Spring MVC 为文件上传提供了直接的支持,Spring MVC 提供了一个文件上传的解析类CommonsMultipartResolver
,即插即用(在XML文件装配下),该类依赖了Apache Commons FileUpload
技术,所以需要导入commons-fileupload.jar
和commons-io.jar
两个包。
上传文件,必须将表单的method
设置为post
,并将enctype
设置为multipart/form-data
,浏览器才会把文件二进制数据发给服务器。
MultipartFile
MultipartFile提供了获取上传文件内容、文件名等方法,transferTo()
可将文件存储到磁盘中。
- String getName():获取表单中文件组件的名字。
- String getOriginalFilename():获取上传文件的原名。
- String getContentType():获取文件
MIME
类型,如image/jpeg等。 - boolean isEmpty():判断是否有上传文件。
- long getSize():获取文件的字节大小,单位 bytes。
- byte[] getBytes():获取文件数据(字节数组)。
- InputStream getInputStream():获取文件流。
- void transferTo(File dest):将上传文件保存到一个目标文件中。
示例代码
上传
java
代码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"; } } }
springmvc.xml
装配CommonsMultipartResolver
类。<!-- 配置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>
对象接收文件
在实体类文件定义
MultipartFile
类型的属性,如下:private MultipartFile headImage;// 头象
Controller
方法使用对象来接收文带有上传文件的from
表单提交的数据。
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载