springBoot 默認傳輸文件大小未1M,超過1M的情況下會報錯。(以下傳輸格式均爲multipart/form-data)
2019-07-27 20:38:40.147 ERROR 15788 --- [nio-8080-exec-3] 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 (35020920) exceeds the configured maximum (10485760)] with root cause
org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (35020920) exceeds the configured maximum (10485760)
at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl
....
修改的做法爲:(springBoot v2.1.6.RELEASE)
#配置文件傳輸
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
#單個文件的最大上限
spring.servlet.multipart.max-file-size=100MB
#單個請求的文件總大小上限
spring.servlet.multipart.max-request-size=1000MB
但是實際應用中這種設置是不滿足我們的需求的,因爲在傳輸文件超過設置閾值後,會報500的錯誤。所以我們應該攔截這個異常,返回我們需要的內容。
另外一個問題,如果是在controller獲知service中做文件大小的限制,那麼在限制文件大小爲20M,可是上傳文件大小爲1G的情況下,需要等1G文件上傳完畢後,才能進入controller進行拒絕應答,這也是個很大的問題。
解決方法之一:
package com.gtn.uplus.filemgr.errutil;
import com.gtn.uplus.filemgr.domain.response.UploadFileResp;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
/**
* @author :Czc
* @date :Created in 2019/7/26 15:30
* @description:
* @modified By:
* @version: $
*/
@RestControllerAdvice
public class MyExceptionHandler {
/***
* 默認上傳大小20MB 超出大小捕獲異常MultipartException
* */
@ExceptionHandler(MultipartException.class)
public UploadFileResp catchException(MultipartException e) {
return new UploadFileResp(ErrNo.ERROR_CONTENT_LIMITED,ErrNo.getErrorInfo(ErrNo.ERROR_CONTENT_LIMITED),null);
}
}