Spring Boot 默认上传文件大小限制是 1MB,默认单次请求大小是 10MB,超出大小会跑出 MaxUploadSizeExceededException 异常
解决方案:yaml新增配置如下:
#最最最重要的一行,修改tomact吞吐量,这里不限制
server:
tomcat:
max-swallow-size: -1
注意上面最重要的是要配置内嵌的 tomcat 的最大吞吐量即 max-swallow-size,可以设置 -1 不限制,也可以设置一下比较大的数字。当上传文件超 tomcat 的大小限制后会先于 Controller 触发异常,所以这时我们的异常处理类无法捕获 Controller 层的异常。
增加完该配置后当上传文件超大小限制后就可以被全局异常处理类捕获了。
创建一个全局异常处理类来捕获异常:
import com.alibaba.fastjson.JSON;
import com.wuzenglin.enty.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String exception(MaxUploadSizeExceededException e){
if (e.getCause().getCause() instanceof FileSizeLimitExceededException){//单个文件大小超出限制抛出的异常
log.error("message异常信息为=========》"+e.getMessage());
log.error("cause异常信息为=========》"+e.getCause().getCause());
Result result = new Result(104, null, "单个上传文件大小不能超过20MB", null);
String s = JSON.toJSONString(result);
return s;
}else if (e.getCause().getCause() instanceof SizeLimitExceededException){//总文件大小超出限制抛出的异常
log.error("message异常信息为=========》"+e.getMessage());
log.error("cause异常信息为=========》"+e.getCause().getCause());
Result result = new Result(104, null, "总上传文件大小不能超过200MB", null);
String s = JSON.toJSONString(result);
return s;
}
return "上传文件异常";
}
}
截图展示:
参考链接:
https://weiku.co/article/198/
https://blog.csdn.net/daweozai/article/details/103575718