Reputation: 2915
I have a REST API implemented through Spring Boot. I need to serve multipart/form-data
requests (a JSON and a list of images) and I do so through this simple controller method:
@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);
}
To constrain the size of the uploaded files, I have the following in my application.properties
:
# Constrain maximum sizes of files and requests
spring.http.multipart.max-file-size=20MB
spring.http.multipart.max-request-size=110MB
I tested the behavior of these keys by uploading a big file, and while they work well, the returned message to the user is not particularly informative of what happened:
{
"timestamp": "2021-01-05T14:07:14.577+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "",
"path": "/rest/products"
}
Is there any way for me to have SpringBoot automatically supply a message
in the case of too large of a file uploaded, or can I only do this through my own custom controller logic in the postProduct
method shown above?
Upvotes: 0
Views: 212
Reputation: 3370
You need to handle MaxUploadSizeExceededException
by using either a HandleExceptionResolver
or a ControllerAdvice
(or a RestControllerAdvice
).
Something like this:
@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);
}
}
Upvotes: 1