SpringBoot配置文件上传限制

MultipartFile文件上传限制

spring:
  # 文件大小限制
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

加入全局异常拦截器

@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {

    /**
     * 文件上传异常
     */
    @ExceptionHandler(MultipartException.class)
    public R handleException(MultipartException e) {
        log.error("Exception,exception:{}", e, e);
        BaseResponseCode em = e.getBaseResponseCode();
        return new R(em.getCode(), "文件过大,请上传小于100M文件!");
    }

    /**
     * 自定义全局异常处理
     */
    @ExceptionHandler(value = BusinessException.class)
    R businessExceptionHandler(BusinessException e) {
        log.error("Exception,exception:{}", e, e);
        BaseResponseCode em = e.getBaseResponseCode();
        return new R(em.getCode(), em.getMsg());
    }

    /**
     * 处理参数格式校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("参数格式校验异常");
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errorMap = Maps.newHashMap();
        AtomicReference<String> errorMsg = new AtomicReference<>("");
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMsg.set(fieldError.getDefaultMessage());
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.fail(errorMsg);
    }

    /**
     * 校验List<entity>类型, 需要controller添加@Validated注解
     * 处理Validated List<entity> 异常
     */
    @ExceptionHandler
    public R handle(ConstraintViolationException exception) {
        log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", exception, exception);
        Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
        StringBuilder builder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations) {
            builder.append(violation.getMessage());
            break;
        }
        return R.getResult(BaseResponseCode.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getCode(), builder.toString());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值