通知用户上传大文件

vi4fp9gy  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(362)

我有一个通过springboot实现的restapi。我需要服务 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 上面显示的方法?

s5a0g9ez

s5a0g9ez1#

你需要处理 MaxUploadSizeExceededException 通过使用 HandleExceptionResolver 或者 ControllerAdvice (或 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);
    }

}

相关问题