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

vol*_*a89 8 java spring spring-boot

我正在使用 Spring Boot 2.1.3(使用标准的 Tomcat 嵌入式 Web 服务器)开发一个端点来上传图像,我想限制分段上传的大小。我可以使用以下属性轻松做到这一点:

spring:
    servlet:
        multipart:
            max-file-size: 2MB
            max-request-size: 2MB
Run Code Online (Sandbox Code Playgroud)

但是我总是得到一个 Spring 无法捕获的 500,因为 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)
Run Code Online (Sandbox Code Playgroud)

我的 ExceptionHandler 是这样的,但显然无论注释中出现什么异常都不起作用:

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

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

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

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

有人为此而苦苦挣扎吗?

小智 14

请将此添加到您的application.properties

spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB
Run Code Online (Sandbox Code Playgroud)

您可以根据需要在上面的配置中更改大小

  • 感谢您的帮助,但您应该仔细阅读问题。在第一段中我已经说过我已经尝试过这些属性。 (4认同)
  • 它应该是“MB”而不是“Mb” (3认同)

pet*_*o16 5

有点晚了。您需要在 application.properties 或 application.yml 中进行设置, server.tomcat.max-swallow-size=-1 有了它 tomcat 将不会干扰上传请求,并且操作将由 spring 完全处理,您的异常控制器将完美运行。 参考