多部分文件上传:Spring Boot 中超出大小限制的异常返回 JSON 错误信息。

8

我已经设置了最大文件上传限制,所以我遇到了

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 2097152 bytes 

上传文件时出现错误。我的api返回500错误,我该如何处理这个错误并以JSON格式返回响应,而不是像ErrorController中提供的错误页面。

我想捕获异常并提供JSON响应,而不是ErrorPage

@RequestMapping(value="/save",method=RequestMethod.POST)
    public ResponseDTO<String> save(@ModelAttribute @Valid FileUploadSingleDTO fileUploadSingleDTO,BindingResult bindingResult)throws MaxUploadSizeExceededException
    {
        ResponseDTO<String> result=documentDetailsService.saveDocumentSyn(fileUploadSingleDTO, bindingResult);

        return result;

    }

接受以下文件的DTO

public class FileUploadSingleDTO {
@NotNull
    private Integer documentName;

    private Integer documentVersion;

    @NotNull
    private MultipartFile file;
}

我想捕获文件大小超过异常的情况...在上传大文件后。当我上传小于MaxUploadSize的文件大小时,我的代码运行良好。 - MasterCode
你的文件上传处理代码是什么? - Rana_S
你也可以使用MultipartHttpServletRequest代替HttpServletRequest。然后,要访问上传的文件,你只需要使用MultipartFile file = request.getFile(request.getFileNames().next());,你需要将其包装在一个IOException中。这样可以保持你的DTO简洁。 - Sean Perkins
2个回答

18

据我所知,你可以使用以下方法处理多部分文件异常。

@ControllerAdvice
public class MyErrorController extends ResponseEntityExceptionHandler {

Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());

@ExceptionHandler(MultipartException.class)
@ResponseBody
String handleFileException(HttpServletRequest request, Throwable ex) {
    //return your json insted this string.
    return "File upload error";
  }
}

1
在深入研究源代码后,我发现CommonsMultipartResolver正在处理FileSizeLimitExceededException异常,并在此处抛出throw new MultipartException("Could not parse multipart servlet request", ex); 这里的ex是FileSizeLimitExceededException,实际上是由commons.fileupload.FileuploadBase类抛出的。因此,您无法处理FileSizeLimitExceededException。请使用MultipartException来处理通用的文件上传错误。 - Srinivas Rampelli
2
@RampelliSrinivas 如果您能稍微解释一下您上面写的评论,那将非常有帮助。 - quintin

4
在您的控制器中添加一个特殊的异常处理程序:
@ExceptionHandler(FileSizeLimitExceededException.class)
public YourReturnType uploadedAFileTooLarge(FileSizeLimitExceededException e) {
    /*...*/
}

如果这不起作用,您需要在配置中启用异常处理。通常Spring会默认启用此功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接