【发布时间】:2021-01-05 14:21:05
【问题描述】:
我有一个通过 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"
}
如果上传的文件太大,我有什么办法让 SpringBoot 自动提供message,或者我只能通过上面显示的postProduct 方法中的我自己的自定义控制器逻辑来做到这一点?
【问题讨论】:
-
您可以使用
@ExceptionHandler或@restControllerAdvice捕获错误,并为您的用户自定义消息。
标签: java spring-boot rest multipartform-data