Springboot:文件上传大小超出限制异常捕获并输出信息

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

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值