2014-12-02 49 views
0

我正在使用Spring-MVC構建寧靜的服務。 使用多部分表單提供POST請求時,我想限制發佈的文件大小。 通常的方法是如下:Servlet 3.0 multipart-config無法在最大文件大小下工作

<web-app version="3.0"... 

//...other code omitted 

<servlet> 
    <servlet-name>restful</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/spring/appServlet/restful-context.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
    <multipart-config> 
     <max-file-size>500</max-file-size> 
    </multipart-config> 
</servlet> 

我的寧靜-context.xml的是這樣的:

<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 

    <mvc:annotation-driven> 
    <mvc:message-converters> 
     <beans:bean 
      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> 
    </mvc:message-converters> 
    </mvc:annotation-driven> 

    <beans:bean 
    class="org.springframework.web.multipart.support.StandardServletMultipartResolver" 
    id="multipartResolver" /> 

    //... 
</beans:beans> 

上面是什麼PRO SPRING 4告訴我這樣做。 但最大文件大小不生效。我試着發佈一個非常大的文件(接近1GB),並沒有拋出異常。 任何人都可以幫忙嗎?


後來我刪除了DispatcherServlet的配置從web.xml中,而不是我試過annotaion風格採用@MultipartConfig,如下(感謝@RE350):

@WebServlet(loadOnStartup = 1, name = "restful", urlPatterns = { "/restful/*" }, initParams = { @WebInitParam(name = "contextConfigLocation", value = "/WEB-INF/spring/appServlet/restful-context.xml") }) 
@MultipartConfig(maxFileSize = 500) 
public class MyDispatcherServlet extends DispatcherServlet {} 

它workded! 那麼爲什麼web.xml的方式不起作用?等待你的答覆。

+0

你在哪裏託管應用程序,可它不是一個Servlet容器3+ ? – 2014-12-02 16:33:14

+0

@BijuKunjummen我正在使用STS內置的Pivotal tc Server,它應該使用嵌入式tomcat 8.0.9 – ldn0x7dc 2014-12-03 02:24:57

回答

2

我認爲max-file-size的值是以字節爲單位的,你必須像下面那樣乘以500 1024 * 1024。

 <multipart-config> 
     <max-file-size>524288000</max-file-size> 
     <max-request-size>524288000</max-request-size> 
    </multipart-config> 

更多了,如果你正在使用Spring MVC的,你也可以使用@MultiPartConfig標註上你的Spring服務就像下面。

@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024, 
    maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5) 
0

你既需要最大文件大小和最大請求​​大小和文件大小閾值

<multipart-config> 
    <max-file-size>500</max-file-size> 
    <max-request-size>700</max-request-size> 
    <file-size-threshold>0</file-size-threshold> 
</multipart-config>