Spring文件上传与AJAX太大错误

时间:2018-10-19 14:10:38

标签: spring-boot

我正在通过jQuery ajax上传文件,因此无论如何都希望有适当的响应。我现在正在为我在application.properties中设置的大小限制苦苦挣扎:

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

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

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

Multipart File Upload:Size exceed exception in spring boot return JSON error message

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

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);
    }

}

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

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

# By default they're both "2MB"

server.tomcat.max-swallow-size=-1
server.tomcat.max-http-form-post-size=-1

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