一、文件上传
• Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的MultipartResolver 实现的。
• Spring 用Jakarta Commons FileUpload 技术实现了一个MultipartResolver 实现类:CommonsMultipartResovler
• Spring MVC 上下文中默认没有装配MultipartResovler,因此默认情况下不能处理文件的上传工作,要使用Spring的文件上传功能,需现在上下文中配置MultipartResolver
二、配置MultipartResolver
• defaultEncoding: 必须和用户JSP 的pageEncoding 属性一致,以便正确解析表单的内容
• 为了让CommonsMultipartResovler 正确工作,必须先将Jakarta Commons FileUpload 及Jakarta Commons io的类包添加到类路径下。
三、示例
1、导入commonsFileupload jar包,commons-io jar包
2、在springmvc.xml配置文件中配置MultipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="1024000"></property> </bean>
3、编写handlers@RequestMapping("/testFileUpload") public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file,Map<String,Object> map) throws IOException { System.out.println("desc = " + desc); System.out.println("filename = " + file.getOriginalFilename()); System.out.println("size = " + file.getSize()); System.out.println("getInputStream" + file.getInputStream()); map.put("filename", file.getOriginalFilename()); map.put("filesize", file.getSize()); map.put("InputStream", file.getInputStream()); return "success"; }
4、form
<form action="testFileUpload" method="POST"
enctype="multipart/form-data">
File:<input type="file" name="file" /> Desc:<input type="text"
name="desc" /> <input type="submit" value="Submit" />
</form>
5、
Filename:${requestScope.filename }
<br>
<br>
<br> filesize:${requestScope.filesize }
<br>
<br>
<br> InputStream:${requestScope.InputStream }
<br>
<br>
<br>