![](/img/trans.png)
[英]Java/Spring MaxUploadSizeExceededException post parameters
[英]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.