Spring Boot-分段文件最大上传大小例外

时间:2019-03-02 11:49:59

标签: java spring spring-boot

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

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

但是我总是得到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)

我的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;
}

我已经检查了以下问题(及其他问题)的答案,但它们大多已过时或根本无法使用:

有人在为此苦苦挣扎吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

请在您的application.properties中添加它:

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

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