Spring Boot 默認上傳文件大小限制是 1MB,默認單次請求大小是 10MB,超出大小會跑出 MaxUploadSizeExceededException 異常。
問題出現了,當文件超過 1M 和超過 10M 時異常是有區別的,這也是本文所說的重點。
解決方案
spring:
servlet:
multipart:
max-request-size: 15MB #改為自己的想要的
max-file-size: 5MB #改為自己的想要的
enabled: true
server:
tomcat:
max-swallow-size: 100MB #重要的一行,修改tomcat的吞吐量
注意上面最重要的是要配置內嵌的 tomcat 的最大吞吐量即 max-swallow-size,可以設置 -1 不限制,也可以設置一下比較大的數字這里我設置 100M。當上傳文件超 tomcat 的大小限制后會先于 Controller 觸發異常,所以這時我們的異常處理類無法捕獲 Controller 層的異常。
使用全局異常處理類來捕獲異常
@RestControllerAdvice
public class GlobalExceptionHandler {
static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = MultipartException.class)
public @ResponseBody
Response handleBusinessException(MaxUploadSizeExceededException ex) {
String msg;
if (ex.getCause().getCause() instanceof FileUploadBase.FileSizeLimitExceededException) {
logger.error(ex.getMessage());
msg = "上傳文件過大[單文件大小不得超過10M]";
} else if (ex.getCause().getCause() instanceof FileUploadBase.SizeLimitExceededException) {
logger.error(ex.getMessage());
msg = "上傳文件過大[總上傳文件大小不得超過10M]";
} else {
msg = "上傳文件失敗";
}
return new Response("-1", msg, null);
}
}