java SpringBoot 当文件上传大小限制超过获取 MultipartException 而不是 MaxUploadSizeExceededException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35379748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SpringBoot When file upload size limit exceeds getting MultipartException instead of MaxUploadSizeExceededException
提问by K. Siva Prasad Reddy
I have simple SpringBoot app file uploading functionality where max file upload file size is 2 MB.
我有简单的 SpringBoot 应用程序文件上传功能,其中最大文件上传文件大小为 2 MB。
I have configured multipart.max-file-size=2MB
it is working fine.
But when I try to upload files with larger than 2 MB size I want to handle that error and show the error message.
我已经配置multipart.max-file-size=2MB
它工作正常。但是当我尝试上传大于 2 MB 的文件时,我想处理该错误并显示错误消息。
For that I have my controller implements HandlerExceptionResolver
with resolveException()
implementation as follows:
为此,我的控制器实现HandlerExceptionResolver
了resolveException()
如下实现:
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception exception)
{
Map<String, Object> model = new HashMap<String, Object>();
if (exception instanceof MaxUploadSizeExceededException)
{
model.put("msg", exception.getMessage());
} else
{
model.put("msg", "Unexpected error: " + exception.getMessage());
}
return new ModelAndView("homepage", model);
}
The problem is the Exception Im getting is MultipartExceptioninstead of MaxUploadSizeExceededException.
问题是我得到的异常是MultipartException而不是MaxUploadSizeExceededException。
The stacktrace is: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field myFile exceeds its maximum permitted size of 2097152 bytes.
堆栈跟踪是: 无法解析多部分 servlet 请求;嵌套异常是 java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: 字段 myFile 超过其最大允许大小 2097152 字节。
In the case of file size exceeds why not I am getting MaxUploadSizeExceededException? I am getting its parent Exception MultipartExceptionwhich can be occured for many other reasons in addition to File Size exceeds.
在文件大小超过的情况下,为什么我没有得到MaxUploadSizeExceededException?我得到了它的父异常MultipartException,除了文件大小超出之外,还有许多其他原因可能会发生这种异常。
Any thoughts on this?
对此有何想法?
回答by aalmero
I faced the same issue, it looks like only the MultipartResolver of Commons File Upload implementation throws MaxUploadSizeExceededException but not the MultipartResolver Servlet 3.0 implementation.
我遇到了同样的问题,看起来只有 Commons File Upload 的 MultipartResolver 实现抛出 MaxUploadSizeExceededException 而不是 MultipartResolver Servlet 3.0 实现。
Here's what I have done so far. The key here was to allow the file to be check on the controller, then you can validate size and set an error.
这是我到目前为止所做的。这里的关键是允许在控制器上检查文件,然后您可以验证大小并设置错误。
set multipart properties below multipart: max-file-size: -1 max-request-size: -1
set Tomcat 8 (maxSwallowSize="-1")
on controller, add logic to check size
if(fileAttachment.getSize() > 10485760 ) { throw new MaxUploadSizeExceededException(fileAttachment.getSize()); }
在 multipart 下面设置 multipart 属性: max-file-size: -1 max-request-size: -1
设置 Tomcat 8 (maxSwallowSize="-1")
在控制器上,添加逻辑来检查大小
if(fileAttachment.getSize() > 10485760) { throw new MaxUploadSizeExceededException(fileAttachment.getSize()); }
回答by Amol
following values in application.properties worked for me. It seems it make acceptable file size unlimited
application.properties 中的以下值对我有用。它似乎使可接受的文件大小不受限制
multipart.maxFileSize=-1
multipart.maxRequestSize=-1
Now you need to add logic at your controller side.
现在您需要在控制器端添加逻辑。
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
long size = file.getSize();
if(size > 10000000)
{
redirectAttributes.addFlashAttribute("message",
"You file " + file.getOriginalFilename() + "! has not been successfully uploaded. Requires less than 10 MB size.");
return "redirect:/upload";
}
}
回答by Brice Roncace
It's not great, but my quick and dirty solution was to check to see if the MultipartException
message String contained the text SizeLimitExceededException
and extract the maximum file size information from that message.
这不是很好,但我快速而肮脏的解决方案是检查MultipartException
消息字符串是否包含文本SizeLimitExceededException
并从该消息中提取最大文件大小信息。
In my case, the exception being thrown on tomcat 8.0.x was org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (177351) exceeds the configured maximum (2048)
在我的例子中,tomcat 8.0.x 上抛出的异常是org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:请求被拒绝,因为它的大小 (177351) 超过了配置的最大值 (2048)
Keep in mind, as aalmero pointed out, if you use the CommonsMultipartResolver
rather than the StandardServletMultipartResolver
, a MaxUploadSizeExceededException
would be thrown which is much nicer to handle. The following code handles a MultipartException
thrown by either multipart resolver strategy:
请记住,正如 aalmero 指出的那样,如果您使用 theCommonsMultipartResolver
而不是StandardServletMultipartResolver
,MaxUploadSizeExceededException
则会抛出 a ,这更好处理。以下代码处理MultipartException
由多部分解析器策略引发的异常:
@ControllerAdvice
public class MultipartExceptionExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleMultipartException(MultipartException ex, RedirectAttributes ra) {
String maxFileSize = getMaxUploadFileSize(ex);
if (maxFileSize != null) {
ra.addFlashAttribute("errors", "Uploaded file is too large. File size cannot exceed " + maxFileSize + ".");
}
else {
ra.addFlashAttribute("errors", ex.getMessage());
}
return "redirect:/";
}
private String getMaxUploadFileSize(MultipartException ex) {
if (ex instanceof MaxUploadSizeExceededException) {
return asReadableFileSize(((MaxUploadSizeExceededException)ex).getMaxUploadSize());
}
String msg = ex.getMessage();
if (msg.contains("SizeLimitExceededException")) {
String maxFileSize = msg.substring(msg.indexOf("maximum")).replaceAll("\D+", "");
if (StringUtils.isNumeric(maxFileSize)) {
return asReadableFileSize(Long.valueOf(maxFileSize));
}
}
return null;
}
// http://stackoverflow.com/a/5599842/225217
private static String asReadableFileSize(long size) {
if(size <= 0) return "0";
final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}