我有一个 Spring MVC web,它有两个不同的页面,它们有不同的表单来上传不同的文件。其中一个应该有 2MB 的限制,而另一个应该有 50MB 的限制。
现在,我的 app-config.xml 中有这个限制:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes (2097152 B = 2 MB) -->
<property name="maxUploadSize" value="2097152 "/>
</bean>
我可以像这样在我的主 Controller 中解决 maxUploadSize 异常:
@Override
public @ResponseBody
ModelAndView resolveException(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception exception) {
ModelAndView modelview = new ModelAndView();
String errorMessage = "";
if (exception instanceof MaxUploadSizeExceededException) {
errorMessage = String.format("El tamaño del fichero debe ser menor de %s", UnitConverter.convertBytesToStringRepresentation(((MaxUploadSizeExceededException) exception)
.getMaxUploadSize()));
} else {
errorMessage = "Unexpected error: " + exception.getMessage();
}
saveError(arg0, errorMessage);
modelview = new ModelAndView();
modelview.setViewName("redirect:" + getRedirectUrl());
}
return modelview;
}
但这显然只控制了 2MB 的限制。我怎么能限制20MB的呢? 我试过这个解决方案:https://stackoverflow.com/a/11792952/1863783 ,它更新了运行时的限制。但是,这会为每个 session 和每个 Controller 更新它。因此,如果一个用户正在为第一种形式上传文件,则另一个使用第二种形式上传的用户应该具有第一种形式的限制...
有什么帮助吗?谢谢
最佳答案
乍一看这似乎不是最佳解决方案,但这取决于您的要求。
您可以为所有 Controller 设置一个具有最大上传大小的全局选项,并为特定 Controller 使用较低的值覆盖它。
application.properties 文件(Spring Boot)
spring.http.multipart.max-file-size=50MB
带检查的上传 Controller
public void uploadFile(@RequestPart("file") MultipartFile file) {
final long limit = 2 * 1024 * 1024; // 2 MB
if (file.getSize() > limit) {
throw new MaxUploadSizeExceededException(limit);
}
StorageService.uploadFile(file);
}
如果文件大于 2MB,您将在日志中看到此异常:
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 2097152 bytes exceeded
关于java - 根据 Controller 更改文件大小限制 (maxUploadSize),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16585866/