首页 > 解决方案 > 大文件上传通知用户

问题描述

我有一个通过 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上面显示的方法中做到这一点?

标签: javaspring-bootrestmultipartform-data

解决方案


您需要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);
    }

}

推荐阅读