多部分文件上载:弹出引导返回JSON错误消息中的大小超过异常

Mas*_*ode 5 spring multipartform-data spring-mvc spring-boot

因为我设置了最大文件上传限制,所以我得到了

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 2097152 bytes 
Run Code Online (Sandbox Code Playgroud)

上传文件时出错.我的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;

    }
Run Code Online (Sandbox Code Playgroud)

接受文件的DTO如下

public class FileUploadSingleDTO {
@NotNull
    private Integer documentName;

    private Integer documentVersion;

    @NotNull
    private MultipartFile file;
}
Run Code Online (Sandbox Code Playgroud)

Sri*_*lli 16

我知道你可以通过使用它来处理多部分文件异常.

@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";
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @RampelliSrinivas 如果您能稍微解释一下您上面写的评论,那将非常有帮助。 (2认同)