多部分文件上载:spring引导返回JSON错误消息中的大小超出异常
由于我已经设置了最大文件上传限制,我得到了多部分文件上载:spring引导返回JSON错误消息中的大小超出异常,spring,spring-mvc,spring-boot,multipartform-data,Spring,Spring Mvc,Spring Boot,Multipartform Data,由于我已经设置了最大文件上传限制,我得到了 org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 2097152 bytes 上传文件时出错。我的api有500个错误,我应该处理此错误并以JSON格式返回响应,而不是ErrorController 我希望捕获该异常并给出J
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;
}
将特殊异常处理程序添加到控制器中:
@ExceptionHandler(FileSizeLimitExceededException.class)
public YourReturnType uploadedAFileTooLarge(FileSizeLimitExceededException e) {
/*...*/
}
(如果这不起作用,则必须在配置中启用异常处理。通常Spring默认情况下这样做)。
@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";
}
}
我想捕获文件大小超过异常。上传大文件后。当我上传的文件大小小于MaxUploadSize时,我的代码工作正常。处理文件上传的代码是什么?您也可以使用
multipartTTpServletRequest
而不是HttpServletRequest
。然后,要访问上载的文件,只需使用MultipartFile file=request.getFile(request.getFileNames().next())
,您需要使用IOException
包装它。在深入研究源代码之后,我发现CommonMultipartResolver正在处理FileSizeLimitExceedeException异常并抛出抛出新的MultipartException(“无法解析多部分servlet请求”,ex);这里ex是FileSizeLimitExceedeException,它实际上是由commons.fileupload.FileuploadBase类引发的。因此,您无法处理FileSizeLimitExceedeException。使用MultipartException时使用泛型实现文件上载错误。@RampelliSrinivas如果您能稍微解释一下上面写的注释,这将非常有帮助。
@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";
}
}