Have you ever tried to upload a photo to a website only to be met with a cryptic error message? That's exactly what I experienced when I tried to upload photos in the BMW reviews. Here I'm going to share how I solved this common but frustrating issue in our Spring Boot application.
I got this error when I tried to upload a 'test' image which was 1.5 MB big.
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
This error occurs when someone tries to upload a file that's larger than what our server is configured to handle. Think of it like trying to fit an oversized package through a small mail slot.
First, we needed to tell our application exactly how big of a file it should accept. We did this by adding 2 important lines to our application.properties
file:
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
Let me break down what these settings mean:
max-file-size
: This is like setting a size limit for each individual file. We chose 5MB as a reasonable limit that allows for good quality photos while preventing enormous files from being uploaded.max-request-size
: This is the total size limit for all files in a single upload request. We set it to match our individual file size limit since we're handling one photo at a time.While setting the size limits was important, we also wanted to make sure our users got a friendly message if they tried to upload a file that was too large. That's where our custom exception handler came in:
package findmybmw.backend.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity<String> handleMaxSizeException(MaxUploadSizeExceededException exc) {
return ResponseEntity
.status(HttpStatus.PAYLOAD_TOO_LARGE)
.body("File size exceeds the maximum allowed limit!");
}
}
This code does something really helpful: instead of showing users a technical error message, it catches the exception and returns a clear, friendly message explaining what went wrong. Let's break down how it works:
@ControllerAdvice
: This annotation tells Spring that this class handles exceptions across our entire application.@ExceptionHandler
: This specifies which type of exception we're handling (in this case, the MaxUploadSizeExceededException).handleMaxSizeException
method transforms the technical error into a user-friendly message.