实现图片上传
用户必须能够上传图片,因此需要文件上传的功能。比较常见的文件上传组件有Commons FileUpload(http://jakarta.apache.org/commons/fileupload/a>)和COS FileUpload(http://www.servlets.com/cos),spring已经完全集成了这两种组件,这里我们选择Commons FileUpload。
1) 在pom.xml中添加jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
2) 由于Post一个包含文件上传的Form会以multipart/form-data请求发送给服务器,必须明确告诉DispatcherServlet如何处理MultipartRequest。首先在dispatcher-servlet.xml中声明一个MultipartResolver:
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 设置上传文件的最大尺寸为1MB -->
- <property name="maxUploadSize">
- <value>1048576</value>
- </property>
- </bean>
这样一旦某个Request是一个MultipartRequest,它就会首先被MultipartResolver处理,然后再转发相应的Controller。
3) 在UploadImageController中,将HttpServletRequest转型为MultipartHttpServletRequest,就能非常方便地得到文件名和文件内容:
- public ModelAndView handleRequest(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- // 转型为MultipartHttpRequest:
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- // 获得文件:
- MultipartFile file = multipartRequest.getFile(" file ");
- // 获得文件名:
- String filename = file.getOriginalFilename();
- // 获得输入流:
- InputStream input = file.getInputStream();
- // 写入文件
- // 或者:
- File source = new File(localfileName.toString());
- multipartFile.transferTo(source);
- }
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request
.getSession().getServletContext());
commonsMultipartResolver.setDefaultEncoding("utf-8");
multipartRequest = commonsMultipartResolver.resolveMultipart(request);