Home > Back-end >  Handling MaxUploadSizeExceededException in java spring boot
Handling MaxUploadSizeExceededException in java spring boot

Time:12-24

There is endpoint to upload a file and there is max file size defined in application.properties.

If I'm uploading large file it's not even going inside uploadFile function and it just throwing MaxUploadSizeExceededException

In that case I would like to return some specific response status/message like in an example below.

I tried to remove configuration for max-file-size from application.properties but it didn't help.

Any ideas how properly handle this case ?

    @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)

CodePudding user response:

Set spring.servlet.multipart.resolve-lazily to true, then add an ExceptionHandler for MaxUploadSizeExceededException.

application.properties:

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

Controller:

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