Spring中文件上传与下载大小限制与自定义异常拦截

294 阅读1分钟

1、在application.yml中配置相关大小

 servlet:
    multipart:
      max-file-size: 512000 #文件上传与下载大小限制
      max-request-size: 512000

2、自定义异常捕获拦截

import com.imooc.utils.IMOOCJSONResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@RestControllerAdvice
public class CustomExceptionHandler {

    // MaxUploadSizeExceededException 捕获上传文件超过限制异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public IMOOCJSONResult handleMaxUploadFile(MaxUploadSizeExceededException ex) {
        return IMOOCJSONResult.errorMsg("文件大小不能超过500k");
    }
}