[英]Handling MaxUploadSizeExceededException in java spring boot
There is endpoint to upload a file and there is max file size defined in application.properties
.有上传文件的端点,并且在
application.properties
中定义了最大文件大小。
If I'm uploading large file it's not even going inside uploadFile
function and it just throwing MaxUploadSizeExceededException
如果我上传大文件,它甚至不会进入
uploadFile
函数,它只是抛出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.我试图从
application.properties
中删除最大文件大小的配置,但没有帮助。
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)
Set spring.servlet.multipart.resolve-lazily
to true
, then add an ExceptionHandler
for MaxUploadSizeExceededException
.将
spring.servlet.multipart.resolve-lazily
设置为true
,然后为MaxUploadSizeExceededException
添加一个ExceptionHandler
。
application.properties:应用程序.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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.