接口:org.springframework.web.multipart.MultipartResolver
实现类:org.springframework.web.multipart.support.StandardServletMultipartResolver 配合 servlet 3
org.springframework.web.multipart.commons.CommonsMultipartResolver 需要 Commons FileUpload
1、StandardServletMultipartResolver
<!-- 支持文件的上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />
看源码的注释描述如下:
/**
* Standard implementation of the {@link MultipartResolver} interface,
* based on the Servlet 3.0 {@link javax.servlet.http.Part} API.
* To be added as "multipartResolver" bean to a Spring DispatcherServlet context,
* without any extra configuration at the bean level (see below).
*
* <p><b>Note:</b> In order to use Servlet 3.0 based multipart parsing,
* you need to mark the affected servlet with a "multipart-config" section in
* {@code web.xml}, or with a {@link javax.servlet.MultipartConfigElement}
* in programmatic servlet registration, or (in case of a custom servlet class)
* possibly with a {@link javax.servlet.annotation.MultipartConfig} annotation
* on your servlet class. Configuration settings such as maximum sizes or
* storage locations need to be applied at that servlet registration level;
* Servlet 3.0 does not allow for them to be set at the MultipartResolver level.
*
* @author Juergen Hoeller
* @since 3.1
*/
通过在servlet 上配置 multipart-config 实现单个文件大小和总大小限制;
例如在 web.xml 配置如下:
<servlet>
<servlet-name>dispatchServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/config/dispatch-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- 限制上传文件大小,单个 < 2M ;最多支持 10个文件(20M)-->
<multipart-config>
<max-file-size>2097152</max-file-size> <!-- 2*1024*1024 = 2097152 -->
<max-request-size>20971520</max-request-size> <!-- 10*2*1024*1024 = 20971520 -->
<file-size-threshold>0</file-size-threshold> <!--必填-->
</multipart-config>
</servlet>
只有servlet 3 才支持 multipart-config 配置
2、CommonsMultipartResolver