springMVC中配置CommonsMultipartResolver,介绍MultipartResolver的使用
一、MultipartResolver的配置综述
MultipartResolver是专门处理文件上传的一个类,比如我们在前台上传文件到如FTP服务器。
MultipartResolver的使用:
使用MultipartResolver需要在pom中引入两个包:
1 <!-- 文件上传的相关 -->
2 <dependency>
3 <groupId>commons-fileupload</groupId>
4 <artifactId>commons-fileupload</artifactId>
5 <version>1.2.2</version>
6 </dependency>
7 <dependency>
8 <groupId>commons-io</groupId>
9 <artifactId>commons-io</artifactId>
10 <version>2.0.1</version>
11 </dependency>
同时使用MultipartResovler需要在springMVC的配置文件dispatcher-Servlet.xml中进行以下的配置:
1 <!--配置文件上传相关--> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 <!-- 设定文件上传的最大值--> 4 <property name="maxUploadSize" value="10485760"></property> 5 <!-- 设定文件上传时写入内存的最大值,如果小于这个参数不会生成临时文件,默认为10240 --> 6 <property name="maxInMemorySize" value="4096"></property> 7 <!-- 设定默认编码 --> 8 <property name="defaultEncoding" value="UTF-8"></property> 9 </bean>
当我们发起请求的时候会通过dispatcher-Servlet来拦截请求,DispatcherServlet.java中的checkMultipart方法会调用MultipartResovler类中的isMultipart()方法来判断请求中是否带有文件,返回boolean的值。
1 protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException { 2 if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) { 3 if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) { 4 logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " + 5 "this typically results from an additional MultipartFilter in web.xml"); 6 } 7 else if (hasMultipartException(request) ) { 8 logger.debug("Multipart resolution failed for current request before - " + 9 "skipping re-resolution for undisturbed error rendering"); 10 } 11 else { 12 try { 13 return this.multipartResolver.resolveMultipart(request); 14 } 15 catch (MultipartException ex) { 16 if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) { 17 logger.debug("Multipart resolution failed for error dispatch", ex); 18 // Keep processing error dispatch with regular request handle below 19 } 20 else { 21 throw ex; 22 } 23 } 24 } 25 } 26 // If not returned before: return original request. 27 return request; 28 }
1 boolean isMultipart(HttpServletRequest request);
如果解析到请求中包含的有文件的话就会调用MultipartResovler类的resolveMultipart()方法。
1 MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException;
然后将文件数据解析成 MultipartFile 并封装在 MultipartHttpServletRequest对象中,最后传递给 Controller。
1 public interface MultipartHttpServletRequest extends HttpServletRequest, MultipartRequest
二、MultipartResolver的使用简例:
往往我们在前台通过springMVC实现表单提交的方式来上传文件:
1 <form action="${pageContext.request.contextPath}/请求接口" method="post" enctype="multipart/form-data"> 2 <input type="file" name="file"> 3 <input type="submit" value="提交"> 4 </form>