簡體   English   中英

在 java spring boot 中處理 MaxUploadSizeExceededException

[英]Handling MaxUploadSizeExceededException in java spring boot

有上傳文件的端點,並且在application.properties中定義了最大文件大小。

如果我上傳大文件,它甚至不會進入uploadFile函數,它只是拋出MaxUploadSizeExceededException

在那種情況下,我想返回一些特定的響應狀態/消息,如下例所示。

我試圖從application.properties中刪除最大文件大小的配置,但沒有幫助。

任何想法如何正確處理這種情況?

    @PostMapping("file")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        String contentType = file.getContentType();
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().build();
        }
        if (file.getSize() > MAX_FILE_SIZE_10MB) {
            return ResponseEntity.badRequest().body("File is too large");
        }
        try {
            String filename = file.getOriginalFilename();
            File dbFile = File.builder().name(filename).content(file.getBytes()).mediaType(contentType).build();
            dbFile = fileRepository.save(dbFile);
            return ResponseEntity.ok(dbFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
***application.properties***

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
Servlet.service() for servlet [dispatcherServlet] in context with path [/api] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: 

org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException: the request was rejected because its size (15582677) exceeds the configured maximum (10485760)

spring.servlet.multipart.resolve-lazily設置為true ,然后為MaxUploadSizeExceededException添加一個ExceptionHandler

應用程序.properties:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=true

控制器:

@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity maxUploadSizeExceeded(MaxUploadSizeExceededException e) {
    // handle it here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM