Spring Boot - 多部分文件上传大小异常

20

我正在使用Spring Boot 2.1.3(使用标准的Tomcat嵌入式Web服务器)开发一个端点,用于上传图像,并且我想限制多部分上传的大小。我可以轻松地使用以下属性实现此目的:


spring:
    servlet:
        multipart:
            max-file-size: 2MB
            max-request-size: 2MB

但是我总是得到一个500错误,Spring无法捕获异常,因为是Tomcat抛出的异常,并且请求未到达我的RestController中的代码。

2019-03-02 10:12:50.544 ERROR [] [   o.a.c.c.C.[.[.[/].[dispatcherServlet]] [] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (3917946) exceeds the configured maximum (2097152)] with root cause 
org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (3917946) exceeds the configured maximum (2097152)

我的ExceptionHandler就像这样,但是无论在注释中放入什么异常,它显然都不起作用:

@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity handleMaxSizeException(Exception e) {
    logger.warn(e.getMessage());
    ...
    return status(HttpStatus.PAYLOAD_TOO_LARGE).body(...);
}

我已经尝试过使用先前提到的属性,但没有任何效果:

@Bean
public TomcatServletWebServerFactory containerFactory() {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    factory.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> 
        ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1));
    return factory;
}

我已经检查了以下问题(和其他问题...),但它们大多已过时或根本不起作用:

有人在解决这个问题吗?


我在遵循建议后遇到了这个问题:[ERR] 资源耗尽事件:JVM 无法从堆中分配内存。 - Smart Coder
3个回答

12

请在你的application.properties文件中添加以下内容:

spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB

您可以根据配置中的需要更改大小。

4
谢谢你的帮助,但你应该仔细阅读问题。在第一段中,我已经说过我尝试过那些属性了。 - voliveira89
"50Mb" 对我不起作用。我得到了“无法将java.lang.String转换为org.springframework.util.unit.DataSize”的错误。 - Frans
3
应该使用“MB”而不是“Mb”。 - wildnux
这对我来说非常有效,因为我遇到了类似的问题,但只有大写字母B可以使用,正如所提到的那样。 - Holger Ludvigsen

6
有些晚了。你需要在 application.properties 或 application.yml 中设置 server.tomcat.max-swallow-size=-1,这样 Tomcat 就不会干扰上传请求,操作将完全由 Spring 处理,你的异常控制器也将正常工作。
参考:References

0

我遇到了类似的问题。Tomcat一直抱怨请求超过了配置的最大值(2097152),即使我在全局web.xml中使用了默认设置:

      <max-file-size>52428800</max-file-size>
      <max-request-size>52428800</max-request-size>

最终弄清楚了:我正在开发的servlet类扩展了一个带有@MultipartConfig注释的servlet类,但是我的本地类没有@MultipartConfig注释。因此,请求未被视为多部分,这导致了这个错误。
抛出错误的代码在超类中的这些行中:
//Search through the parts for an uploaded file
for (Part part : request.getParts()) {

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接