我有一个非常简单的文件上传设置与Spring Boot.
我想知道当超过最大文件大小时是否有一种简单的方法来显示错误页面.
我上传了一个非常简单的例子,说明我想要达到的目标on github.
基本上,我们的想法是在全局Spring异常处理程序中捕获MultipartException:
@ControllerAdvice
public class UploadExceptionHandler {
@ExceptionHandler(MultipartException.class)
public ModelAndView handleError(MultipartException exception) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error", exception.getMessage());
modelAndView.setViewName("uploadPage");
return modelAndView;
}
}
处理文件上传的控制器非常简单:
@RequestMapping("/")
public String uploadPage() {
return "uploadPage";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String onUpload(@RequestParam MultipartFile file) {
System.out.println(file.getOriginalFilename());
return "uploadPage";
}
以及与之关联的uploadPage.html百万美元模板:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Upload</title>
</head>
<body>
<div style="color: red" th:text="${error}" th:if="${error}">
Error during upload
</div>
<form th:action="@{/}" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file"/>
<button type="submit" name="save">Submit</button>
</form>
</body>
</html>
这个想法是当文件太大时在同一个上传页面中显示错误消息.
我的理解是,可以配置Spring的MultipartResolver来懒惰地解决异常并能够在Spring级别捕获这些异常(MVC异常处理程序),但是这段代码似乎没有帮助:
@Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
public StandardServletMultipartResolver multipartResolver() {
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(true);
return multipartResolver;
}
所以在我采取过滤器或扩展MultipartResolver之类的极端措施之前……
你知道用Spring MVC处理这些异常的干净方法吗?
回答
感谢@ rossen-stoyanchev.
这是我最终做的事情:
@RequestMapping("uploadError")
public ModelAndView onUploadError(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("uploadPage");
modelAndView.addObject("error", request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE));
return modelAndView;
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(MultipartException.class, "/uploadError"));
}
像魅力一样工作,感觉就像一个优雅的解决方案.
如果有兴趣的话,我在github上更新了项目.
非常感谢!
解决方法:
多部分请求解析在选择处理程序之前发生,因此没有@Controller,因此还没有@ControllerAdvice.您可以使用ErrorController(参见http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-error-handling).
顺便说一句,你不需要@RequestParam.参数类型是MultipartFile就足够了.