AJAX 的 Spring 文件上传太大错误



我正在通过jQuery ajax进行一些文件上传,因此在任何情况下都希望得到适当的响应。我现在正在努力解决我在应用程序属性中设置的大小限制:

spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
spring.http.multipart.enabled=false

我找到了很多教程,甚至一些SO答案,但似乎没有一个对我有用。这里有两个例子:

https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/

分段文件上传:春季启动中大小超过异常返回 JSON 错误消息

我总是得到一个空的响应,并且在日志中看到另一个异常(错误来自我的代码,以查看我的处理程序是否发挥作用:

2018-10-19 15:57:54.183 ERROR 12940 --- [http-nio-9002-exec-2] c.i.p.m.mvc.RestExceptionHandler         : CAUSE: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (12698493) exceeds the configured maximum (5242880)
2018-10-19 15:57:54.185  WARN 12940 --- [http-nio-9002-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: 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 (12698493) exceeds the configured maximum (5242880)

这是我的代码,注释掉的部分是我尝试过的一些变体。

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);
@ExceptionHandler(MultipartException.class)
//@ExceptionHandler(MaxUploadSizeExceededException.class)
@ResponseBody
public String handleTooLargeFiles(HttpServletRequest request, Throwable ex) {
//public ResponseEntity<?> handleTooLargeFiles(HttpServletRequest request, Throwable ex) {
LOGGER.error("CAUSE: " + ex.getCause().getMessage());
return "File size exceeds the allowable limit! (5MB)";
//return new ResponseEntity("File size exceeds the allowable limit! (5MB)", HttpStatus.PAYLOAD_TOO_LARGE);
}
}

我做错了什么?

您还必须为嵌入式 Tomcat 设置属性,以免过早终止请求:

# By default they're both "2MB"
server.tomcat.max-swallow-size=-1
server.tomcat.max-http-form-post-size=-1

(或选择一些大尺寸,如20MB而不是-1(

最新更新