java - 大文件上传通知用户
问题描述
我有一个通过 Spring Boot 实现的 REST API。我需要提供multipart/form-data
请求(一个 JSON 和一个图像列表),我通过这个简单的控制器方法来实现:
@PostMapping(value = "/products", consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
public ResponseEntity<ResponseMessage> postProduct(@NonNull @RequestPart(value = "request") final MyJsonBody postRequest,
@NonNull @RequestPart(value = "files") final List<MultipartFile> files)
{
validateFileTypes(files);
log.info("Request id and name fields: " + postRequest.getProductId() + ", " + postRequest.getProductName() + ".");
log.info("Received a total of: " + files.size() + " files.");
storeFiles(files);
return success("Request processed!", null, HttpStatus.OK);
}
为了限制上传文件的大小,我有以下内容application.properties
:
# Constrain maximum sizes of files and requests
spring.http.multipart.max-file-size=20MB
spring.http.multipart.max-request-size=110MB
我通过上传一个大文件测试了这些键的行为,虽然它们运行良好,但返回给用户的消息并没有特别说明发生了什么:
{
"timestamp": "2021-01-05T14:07:14.577+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "",
"path": "/rest/products"
}
有什么办法让SpringBootmessage
在上传的文件太大的情况下自动提供一个,或者我只能通过我自己的自定义控制器逻辑在postProduct
上面显示的方法中做到这一点?
解决方案
您需要MaxUploadSizeExceededException
使用 aHandleExceptionResolver
或 a ControllerAdvice
(或 a RestControllerAdvice
)来处理。
像这样的东西:
@RestControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler({
MaxUploadSizeExceededException.class
})
public ResponseEntity<Object> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) {
Map<String, Object> body = new HashMap<>();
body.put("message", String.format("Max upload limit exceeded. Max upload size is %d", ex.getMaxUploadSize()));
return ResponseEntity.unprocessableEntity().body(body);
}
}
推荐阅读
- hyperledger-fabric - scripts/createChannel.sh:第 40 行:osnadmin:找不到命令频道创建失败
- php - PHP 简单 Dom、正则表达式替换和自动增加变量
- jenkins - 如何从电子邮件模板中的属性文件中读取属性
- reactjs - 在 React js 中选择选择后如何显示输入
- javascript - 我可以只使用 JavaScript 和 CSS 在 react.js 中制作自定义动画吗?
- javascript - 基于列值(条件)导入另一个电子表格行的通用 Google App 脚本
- javascript - Next.js TypeError: (0 , firebase_auth__WEBPACK_IMPORTED_MODULE_1__.onAuthStateChanged) 不是函数
- google-apps-script - 如何使用 Google Apps 脚本同时刷新和添加 Google 表格中的单元格
- php - 填充嵌套数组 Laravel
- python - 由于缺少 TLS CA 证书,PyInstaller 包执行失败