【发布时间】:2019-07-24 06:52:52
【问题描述】:
我正在使用 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;
}
我已经检查了以下问题(以及其他问题......)的答案,但它们大多已过时或根本不起作用:
- Multipart file maximum size exception - spring boot embbeded tomcat
- MaxUploadSizeExceededException doesn't invoke the exception handling method in Spring
- How to handle MaxUploadSizeExceededException
有人在为此苦苦挣扎吗?
【问题讨论】:
标签: java spring spring-boot