【问题标题】:FileSizeLimitExceededException can not be handled in spring bootSpring Boot 中无法处理 FileSizeLimitExceededException
【发布时间】:2021-03-23 23:47:24
【问题描述】:

当我尝试上传文件时,我收到FileSizeLimitExceededException 异常,我无法在我的控制器类中处理它。

我的异常处理程序如下所示:

@ExceptionHandler(Exception.class)
    public ModelAndView handleFileSizeLimitExceeded(Exception exc) {
        
        System.out.println("In Exception handler");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.findUserByEmail(auth.getName());
         ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("imageUploadMessage", "File too big");
         modelAndView.addObject("currentUser", user);
 
        modelAndView.setViewName("profile");

        return          modelAndView;
    }

我在Stackoverflow 上看到了几个关于这个问题的类似问题,但其中许多没有公认的答案,而且那里提出的答案也无法解决我的问题。 例如,我在异常处理程序中尝试了FileSizeLimitExceededException、MultipartException 和MaxUploadSizeExceededException,但控制器根本没有被触发。 按照here 提出的解决方案,我在propertis 文件中尝试了以下设置:

    spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
server.tomcat.max-swallow-size=100MB
spring.servlet.multipart.resolve-lazily=true

但也没有成功。

有没有办法解决这个问题?

同时,我想返回一个ModelAndView 作为返回语句。

我希望到目前为止有人已经找到了解决这个问题的真正方法:)。

更新 1: 这是异常的屏幕截图:

【问题讨论】:

  • 你测试的文件大小是多少?如果它 > 100MB,我怀疑 Tomcat 会断开连接,您将看不到 ModelAndView 的响应。
  • 另外,如果您提供日志和实际响应会很好
  • @AndreiKovrov 我尝试上传的文件是 16 MB 大小的图片。我用异常的屏幕截图更新了我的问题。

标签: java spring spring-boot tomcat exception


【解决方案1】:

为全局 MaxUploadSizeExceededException 处理定义另一个类。下面的代码只触发 MaxUploadSizeExceededException 异常抛出。

@ControllerAdvice
public class GlobalControllerAdvice {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView handleFileSizeLimitExceeded(HttpServletRequest req, Exception ex) {
        System.out.println("In Exception handler");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.findUserByEmail(auth.getName());
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("imageUploadMessage", "File too big");
        modelAndView.addObject("currentUser", user);

        modelAndView.setViewName("profile");

        return          modelAndView;
    }
}

【讨论】:

  • 很遗憾,您的代码不起作用。我将其更改为某种方式,它似乎更好。但唯一的区别是我的 Eclipse 输出中没有任何错误。但它不会返回当前页面,也不会显示我在modelAndView中设置的消息。
  • 嗨,我已经用 ResponseEntity 响应测试了代码。我看到断点被访问到函数中。您是否尝试在函数中放置任何断点?
  • 我在使用 ControllerAdvice 实现时也触发了该函数,如果我在那里设置断点,我也看到了。你说得对。但似乎返回“ModelAndView”在那里无法正常工作。我无法重定向到我以前在那里的页面。当我以这种方式实现它时,我的eclipse中没有任何异常,也没有返回上一页,但我只看到一个“连接中断”页面。
  • 如果您可以将代码返回到当前页面,请与我分享您的代码。
【解决方案2】:

为了解决我的问题,我只需要在我的pom.xml 文件中更新Spring 的版本即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 2020-04-27
    • 2018-11-13
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    相关资源
    最近更新 更多