该请求被拒绝,因为其大小(5838334)超过了配置的最大值(2097152)

时间:2017-11-30 12:38:59

标签: rest spring-boot

我想处理org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException

我的application.properties文件包含:

spring.http.multipart.max-file-size=2MB
spring.http.multipart.max-request-size=2MB
spring.mvc.throw-exception-if-no-handler-found=true

我尝试使用以下代码处理异常:

@ControllerAdvice
public class ExceptionHandlerRestController
{
    @ExceptionHandler(FileUploadBase.SizeLimitExceededException.class)
     public ResponseEntity<Object>exceptionHandler(FileUploadBase.SizeLimitExceededException e) {
        return new ResponseEntity<Object>("size limit exceeded",new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE);
  }
}

虽然我已经处理了异常,但我收到了异常

Servlet.service() for servlet [dispatcherServlet] in context with path [] 
threw exception [Request processing failed; nested exception is 
org.springframework.web.multipart.MultipartException: Could not parse 
multipart servlet request; org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (5838334) exceeds the configured maximum (2097152)

如何自定义上面的类来处理异常?

2 个答案:

答案 0 :(得分:1)

使用以下代码解决问题

@ExceptionHandler(MultipartException.class)
@ResponseBody
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
public ApiError multipartExceptionHandler(MultipartException e)
{
    Throwable th = e.getCause();
    if( th instanceof IllegalStateException )
    {
        Throwable cause = th.getCause();
        if(cause instanceof  SizeLimitExceededException)
        {
            SizeLimitExceededException ex = (SizeLimitExceededException) cause;
            return new ApiError(HttpStatus.PAYLOAD_TOO_LARGE.value(),"Total size of file(s) should not be more than " + (int)(ex.getPermittedSize()/Math.pow(2, 20)) + " MB");
        }
    }
    return new ApiError(HttpStatus.PAYLOAD_TOO_LARGE.value(),e.getMessage());
}

答案 1 :(得分:0)

尝试更新容器配置,如果您正在使用tomcat,请使用以下配置更新server.xml文件

<Connector connectionTimeout="20000" 
           port="8080" 
           protocol="HTTP/1.1" 
           redirectPort="8443" 
           maxPostSize="52428800" />

将maxPostSize设置为52428800会将上传文件大小增加到50 MB。默认情况下,它设置为2 MB。

有关详细说明,请阅读:https://tomcat.apache.org/tomcat-7.0-doc/config/http.html