社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
问题出现了,当文件超过 1M 和超过 10M 时异常是有区别的,这也是本文所说的重点。
解决方案:
在springboot配置文件中配置如下
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);
}
}
截图展示:
参考链接:
https://blog.csdn.net/qq_36515220/article/details/93361119
https://blog.csdn.net/ifu25/article/details/90173264
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!