java 39 lines · 6 steps

Configuring upload size limits in Spring

Cap multipart upload sizes and turn the resulting overflow exception into a clean HTTP 413 response.

Explained by highlit
1package com.example.uploads.config;
2 
3import jakarta.servlet.MultipartConfigElement;
4import org.springframework.boot.web.servlet.MultipartConfigFactory;
5import org.springframework.context.annotation.Bean;
6import org.springframework.context.annotation.Configuration;
7import org.springframework.util.unit.DataSize;
8import org.springframework.web.bind.annotation.ExceptionHandler;
9import org.springframework.web.bind.annotation.RestControllerAdvice;
10import org.springframework.web.multipart.MaxUploadSizeExceededException;
11import org.springframework.http.HttpStatus;
12import org.springframework.http.ProblemDetail;
13 
14@Configuration
15public class MultipartConfig {
16 
17 @Bean
18 public MultipartConfigElement multipartConfigElement() {
19 MultipartConfigFactory factory = new MultipartConfigFactory();
20 factory.setMaxFileSize(DataSize.ofMegabytes(5));
21 factory.setMaxRequestSize(DataSize.ofMegabytes(15));
22 factory.setFileSizeThreshold(DataSize.ofKilobytes(512));
23 return factory.createMultipartConfig();
24 }
25 
26 @RestControllerAdvice
27 static class UploadSizeAdvice {
28 
29 @ExceptionHandler(MaxUploadSizeExceededException.class)
30 public ProblemDetail handleOversizedUpload(MaxUploadSizeExceededException ex) {
31 ProblemDetail problem = ProblemDetail.forStatusAndDetail(
32 HttpStatus.PAYLOAD_TOO_LARGE,
33 "Uploaded content exceeds the maximum allowed size.");
34 problem.setTitle("Payload Too Large");
35 problem.setProperty("maxFileSizeBytes", ex.getMaxUploadSize());
36 return problem;
37 }
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Enforcing upload limits at the container level rejects oversized requests before they consume memory or disk.
  2. 2A @RestControllerAdvice centralizes exception-to-response mapping so every endpoint returns consistent errors.
  3. 3ProblemDetail gives you a standardized, machine-readable error body with room for custom fields.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Configuring upload size limits in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code