文件上傳超過限制,Spring boot捕獲MaxUploadSizeExceededException

//接受異常
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * MaxUploadSizeExceededException異常的特殊之處在於,當上傳文件的大小超過限制時,它的拋出並是在進入Controller之前,
     * 所以不能在controller中利用註解@ExceptionHandler(MaxUploadSizeExceededException.class)來定義該異常的處理方法;
     * @param e
     * @param redirectAttributes
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public String handleError1(MaxUploadSizeExceededException e, RedirectAttributes redirectAttributes){
        redirectAttributes.addFlashAttribute("message",e.getCause().getMessage());
        //給前臺顯示
        return "redirect:show";
    }
    
}
@Controller
public class FileUploadController {

    @GetMapping("/")
    public String index(){
        return "upload";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            //System.out.println(1);
            redirectAttributes.addFlashAttribute("message", "Please select a file to u pload");
            return "redirect:show";
        }
        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            // UPLOADED_FOLDER ⽂件本地存儲地址
            Path path = Paths.get("D://file//" + file.getOriginalFilename());
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
        } catch (IOException e) {
            System.out.println(10);
            e.printStackTrace();
        }
        return "redirect:show";
    }

    @GetMapping("/show")
    public String show(){
        return "show";
    }
}
@SpringBootApplication
public class Application {

    public static void main(String[] args) throws  Exception{
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public TomcatServletWebServerFactory tomcatEmbedded(){
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer)connector ->{
            if((connector.getProtocolHandler() instanceof AbstractHttp11JsseProtocol<?>)){
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return  tomcat;
    }
}

顯示給前端頁面的結果

 

 

 

show.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:text="${message}">
        <h2 th:text="${message}"></h2>
    </div>
</body>
</html>

 

upload.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
</head>
<body>
    <form method="POST" action="/upload" enctype="multipart/form-data">
        <input type="file" name="file" />
        <br/>
        <br/>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

application.properties

#spring boot上傳文件
#MultipartFile 是 Spring 上傳⽂件的封裝類
#支持上傳的最大文件
spring.servlet.multipart.max-file-size= 100MB
#文件請求最大限制
spring.servlet.multipart.max-request-size= 100MB
#最大吞吐量即 max-swallow-size,可以設置 -1 不限制
server.tomcat.max-swallow-size = -1

如果沒加上server.tomcat.max-swallow-size = -1,前臺頁面顯示的結過會是這個

參考:https://www.cnblogs.com/userrain/p/5433233.html

https://blog.csdn.net/ifu25/article/details/90173264

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章