Spring Boot上传文件过大处理方式(基于Spring Boot2.0)

未分类 一条评论


org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (60835074) exceeds the configured maximum (10485760)

增加配置文件
网上有说修改配置
这样子

multipart<span class="hljs-preprocessor">.maxFileSize</span>=<span class="hljs-number">100</span>Mb (允许上传文件的最大大小)
multipart<span class="hljs-preprocessor">.maxRequestSize</span>=<span class="hljs-number">1000</span>Mb (多部分/表单数据请求所允许的最大大小)

也有说这样子

spring<span class="hljs-preprocessor">.http</span><span class="hljs-preprocessor">.multipart</span><span class="hljs-preprocessor">.maxFileSize</span>=<span class="hljs-number">100</span>Mb (允许上传文件的最大大小)
spring<span class="hljs-preprocessor">.http</span><span class="hljs-preprocessor">.multipart</span><span class="hljs-preprocessor">.maxRequestSize</span>=<span class="hljs-number">1000</span>Mb(多部分/表单数据请求所允许的最大大小)

其实都可以
需在项目中增加如下代码

<span class="hljs-annotation">@Configuration</span>
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FileUploadConfig</span> {</span>

     <span class="hljs-javadoc">/** 
     * 文件上传配置 
     * <span class="hljs-javadoctag">@return</span> MultipartConfigElement 
     */</span>  
    <span class="hljs-annotation">@Bean</span>  
    public MultipartConfigElement multipartConfigElement(  
            <span class="hljs-annotation">@Value</span>(<span class="hljs-string">"${spring.http.multipart.maxFileSize}"</span>) String maxFileSize,  
            <span class="hljs-annotation">@Value</span>(<span class="hljs-string">"${spring.http.multipart.maxRequestSize}"</span>) String maxRequestSize) {  
        MultipartConfigFactory factory = <span class="hljs-keyword">new</span> MultipartConfigFactory();  
        factory.setMaxFileSize(maxFileSize);  
        factory.setMaxRequestSize(maxRequestSize);  
        <span class="hljs-keyword">return</span> factory.createMultipartConfig();  
    }  
}

1条评论

L
Ligz says: 回复

我看了很多文章(包括Baeldung的“MaxUploadSizeExceededException in Spring”),但这里解决我的问题(Spring Boot下),受益了,感谢。

“MaxUploadSizeExceededException in Spring”
https://www.baeldung.com/spring-maxuploadsizeexceeded
上面这篇文章没有解决问题,也许是Spring MVC的解决方法不同于Spring Boot,没有深究。

发表回复

您的电子邮箱地址不会被公开。

昵称 *