Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring multipart size limits: enforce parser and application budgets

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

An upload byte budget limits how much request data reaches parsing and storage.

Download Spring source kit

Two different limit points

Spring Boot exposes multipart max-file-size and max-request-size settings for the servlet parser. Those settings are outside the standalone MockMvc fixture. The checked controller also rejects a part whose reported size exceeds 128 bytes, then reads at most 129 bytes to catch an inconsistent or changing source before storing anything. The oversized test receives 413 and leaves the directory empty.

A parser limit can reject a request before the controller runs. The controller limit still guards the application's own allocation and keeps its contract visible in a unit-scale test. It is not a substitute for reverse-proxy and servlet limits. The import entrypoint checks content and path boundaries after this budget. The test-boundary lesson states what MockMvc cannot prove.

Budget the whole request

Multipart overhead and multiple parts can make the request larger than one file. Configure both per-file and total-request ceilings in the deployed stack, and make the proxy ceiling consistent. Limit row count and field length after CSV parsing too; small bytes can still trigger costly work if interpreted badly. Never call readAllBytes on an unbounded user upload. The fixture's 128-byte value is intentionally tiny so the test can assert the boundary.

Checked source

Java
if (file.getSize() > MAX_BYTES) throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE);
byte[] content;
try (var input = file.getInputStream()) {
    content = input.readNBytes(MAX_BYTES + 1);
}
if (content.length > MAX_BYTES) throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE);

Verification boundary

MultipartReceiptImportTest.rejectsOversizedPartBeforeStorage in the downloadable Spring source kit. The excerpt is shortened; the kit contains the complete test.

Costs and limits

MockMultipartFile materializes bytes before the controller sees them. The test proves controller behavior, not peak memory or container rejection. Production limits need deployment tests that include the proxy and servlet parser; 413 mapping may differ by layer.

Common Mistakes

  • Do not confuse max-file-size with max-request-size.
  • Do not read an unbounded upload into a byte array.
  • Do not infer proxy behavior from standalone MockMvc.

Read next

Spring MVC multipart receipt import: validate before storing, Spring MockMvc multipart tests: what the fixture proves, Spring CSV uploads: reject malformed UTF-8 and an unknown header.

spring
spring-boot
upload-byte-budget
Storage details