Spring Boot File Upload Example, and What Really Happens to the File
Take a @RequestParam("file") MultipartFile in a @PostMapping and copy file.getInputStream() to a path you choose. That works in ten lines. What catches people is everything around it, measured here on Spring Boot 4.1.1: a 1,048,577-byte file gets HTTP 413 with an empty body, the upload lives in a temp file that is deleted the moment your method returns, getBytes() allocated the whole file on the heap, and a filename of ../escaped.txt wrote outside the upload folder.
Every Spring Boot file upload example shows the same ten lines, and they do work. This one shows those lines too, then uploads files that are too big, too many, badly named and lying about their type, and prints what came back. Everything below was run against Spring Boot 4.1.1 (Spring Framework 7.0.9, Tomcat 11.0.24) on Java 25, with curl as the client.
The upload endpoint in ten lines
Generate a project with the Spring Web dependency (creating a Spring Boot project covers that step). You need no other dependency: Spring Boot hands multipart parsing to the servlet container.
@PostMapping("/files")
public Map<String, Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Empty file");
}
String stored = UUID.randomUUID() + extensionOf(file.getOriginalFilename());
Path target = uploadDir.resolve(stored);
try (InputStream in = file.getInputStream()) {
Files.copy(in, target);
}
return Map.of("originalFilename", String.valueOf(file.getOriginalFilename()),
"storedAs", stored, "size", file.getSize(),
"contentType", String.valueOf(file.getContentType()));
}
uploadDir is an absolute, normalized Path created at startup, and extensionOf keeps only a short alphanumeric extension from the last path segment. Both choices are explained further down. Call it:
curl -F "file=@f900k.bin" http://localhost:18401/files
HTTP/1.1 200
{"contentType":"application/octet-stream","storedAs":"67d08ab9-7400-4649-8614-ae8aca08c2d6.bin","originalFilename":"f900k.bin","size":921600}
A missing file part returned 400. So did an empty file. A JSON body sent to the same URL returned 500, logged as MultipartException: Current request is not a multipart request. That is worth handling if your endpoint is public.
The 1MB limit, and the 413 with nothing in it
The Spring Boot documentation says it configures "a maximum size of 1MB per file and a maximum of 10MB of file data in a single request". The limit is inclusive. A file of exactly 1,048,576 bytes was accepted, and a file of 1,048,577 bytes got this:
HTTP/1.1 413
Content-Length: 0
Connection: close
The status is right. The body is empty. Here is the log for one request:
WARN ... DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded]
WARN ... DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded]
The line appears twice because two dispatches happened. With DispatcherServlet debug logging switched on, the sequence is Completed 413 CONTENT_TOO_LARGE, then "ERROR" dispatch for GET "/error", parameters={multipart}. Spring Boot's error page is served by forwarding to /error, and that forward carries the same oversized multipart request, which fails to parse again. The error page therefore can't render anything.
Big files did not reset the connection either. A 200MB upload got the same clean 413 in all eight attempts, and curl had sent only 0.5 to 1.9MB of it when the answer arrived. This was on localhost, so a proxy or a slow network can behave differently.
Common mistake
Raising
max-file-sizeand forgettingmax-request-size. Eleven files of 921,600 bytes (10,137,600 in total) were accepted, and twelve (11,059,200) were rejected against the 10,485,760-byte request limit, even though every file was under 1MB.
Does @ControllerAdvice catch MaxUploadSizeExceededException?
A common claim is that it cannot, because the exception is thrown before a controller is chosen. The first half is true: in Spring Framework 7.0.9 doDispatch calls checkMultipart before getHandler. The conclusion is not. On this version a global advice catches it:
@RestControllerAdvice
public class UploadErrors {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ProblemDetail tooLarge(MaxUploadSizeExceededException ex) {
ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.CONTENT_TOO_LARGE,
"File too large. Limit: " + ex.getMaxUploadSize() + " bytes");
body.setTitle("Upload rejected");
return body;
}
}
HTTP/1.1 413
Content-Type: application/problem+json
{"detail":"File too large. Limit: -1 bytes","instance":"/files","status":413,"title":"Upload rejected"}
The handler ran and the caller got a body. But look at the message: getMaxUploadSize() returned -1. With the container's parser the exception does not know the limit, so read it from your own configuration if you want to show it. If you only need a body, spring.mvc.problemdetails.enabled=true with no handler returned {"detail":"Maximum upload size exceeded","instance":"/files","status":413,"title":"Content Too Large"}. That property is covered in the REST API guide.
Logging ex.getCause() shows that one exception covers three different problems:
| What was sent | Cause from Tomcat |
|---|---|
| One 2MB file | FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes. |
| Twelve 921,600-byte files | SizeLimitExceededException: ... its size (11061196) exceeds the configured maximum (10485760) |
| Fifty-one 7-byte files | FileCountLimitExceededException: attachment |
The last row is the surprise. Tomcat's maxPartCount defaults to 50 and counts every part, not just files. Fifty tiny files were accepted and fifty-one returned "Maximum upload size exceeded" while carrying a few hundred bytes. Setting server.tomcat.max-part-count=100 let 51 through.
Where the file is while your method runs
spring.servlet.multipart.file-size-threshold defaults to 0B, so every part goes to disk before your code runs. An endpoint that listed the servlet temp directory during the request found:
tempDir: /private/var/folders/.../T/tomcat.18401.12017605068030106783/work/Tomcat/localhost/ROOT
duringRequest: upload_1a8b404d_c2b1_4736_976c_1725ada67550_00000175.tmp (921600 bytes)
One second after the response, the same listing was []. The temp file is deleted when the request ends, and that has a consequence people find in production. A handler that passed the MultipartFile to a background task and returned straight away logged this a second later:
background read failed: java.nio.file.NoSuchFileException: .../work/Tomcat/localhost/ROOT/upload_..._00000176.tmp
Copy the bytes somewhere you own before returning, then hand the background job that path.
A related trap: file.transferTo(new File("uploads-relative/x.bin")) does not write relative to your working directory. It returned 500 with FileNotFoundException: .../work/Tomcat/localhost/ROOT/uploads-relative/..., because the path was resolved against Tomcat's temp directory. The MultipartFile Javadoc warns that storage "may be container-dependent, including the base directory for relative destinations". Always pass an absolute Path.
getBytes() versus streaming, measured
The limits were raised to 1GB and the app ran with -Xmx256m. Each endpoint recorded getCurrentThreadAllocatedBytes() on the request thread before and after writing the file. The table shows the median of five uploads:
| Method | 50MB file | 200MB file |
|---|---|---|
Files.write(target, file.getBytes()) |
52,431,920 bytes | 209,718,152 bytes |
Files.copy(file.getInputStream(), target) |
4,840 bytes | 9,736 bytes |
file.transferTo(target) |
4,584 bytes | 9,480 bytes |
getBytes() costs exactly one copy of the file. Surprisingly, a single 200MB upload on the 256MB heap succeeded. So the problem isn't one big file, it's two at once. Two concurrent 200MB uploads were tried three times, and every time one returned 500 with java.lang.OutOfMemoryError: Java heap space. Four concurrent 200MB streamed uploads succeeded all three times. The part is already on disk, so streaming just moves bytes from one file to another.
These numbers count allocation on the request thread only, which is where the handler's work happens.
getOriginalFilename() is attacker input
The naive version appears in many tutorials:
Path target = uploadDir.resolve(file.getOriginalFilename());
file.transferTo(target);
curl can send any filename, which makes it easy to test on your own machine:
curl -F "file=@note.txt;filename=../escaped.txt" http://localhost:18401/naive
{"writtenTo":".../run/uploads/escaped.txt","originalFilename":"../escaped.txt"}
The upload folder was .../run/uploads/app. Neither Spring nor Tomcat stripped the ../, and the file landed one level up. With ../../escaped2.txt it went two levels up. With an absolute path as the filename, Path.resolve returned that absolute path and the file was written there. The Javadoc says so directly: the name "could also contain characters such as ".." and others that can be used maliciously".
There are two fixes, and both were tested. The one to prefer is the endpoint at the top: the stored name is a UUID, and ../../evil.txt became 606f49aa-dbc0-428e-b131-225c92db0ec3.txt. If you really need the caller's name, normalize the path and check that it stays inside the folder:
Path target = uploadDir.resolve(file.getOriginalFilename()).normalize();
if (!target.startsWith(uploadDir)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid file name");
}
Both ../escaped.txt and the absolute path returned 400. Make the endpoint authenticated as well. Securing Spring Boot with JWT shows how, and an upload endpoint is one of the first things worth locking down.
The content type is a claim, not a fact
getContentType() returns whatever the client put in the part header. An HTML file containing a <script> tag, sent as type=image/png;filename=cat.png, came back as "claimedContentType":"image/png". Reading the first eight bytes told a different story: "startsWithPngSignature":false. A real PNG returned true.
Checking the signature is better than trusting the header. It still isn't enough on its own. The OWASP File Upload Cheat Sheet says signature validation "should not be used on its own, as bypassing it is pretty common and easy". Use it alongside a generated name and an allow-list of extensions, not instead of them.
Multiple files
Change the parameter to a list:
@PostMapping("/multi")
public List<Map<String, Object>> multi(@RequestParam("files") List<MultipartFile> files) {
curl -F files=@s1.txt -F files=@s2.txt http://localhost:18401/multi
[{"name":"s1.txt","size":7},{"name":"s2.txt","size":7}]
The earlier limits apply to the whole request: 10MB in total, and at most 50 parts.
Streaming without multipart
A multipart upload is always spooled to disk first. If a client can send the raw body instead (PUT with application/octet-stream), you can read request.getInputStream() directly. Then none of the multipart limits apply. On an app with the default 1MB limit, curl -T f200m.bin to such an endpoint returned {"bytes":209715200} with HTTP 200, three times out of three.
So a raw endpoint needs its own limit. The tested version rejects early on Content-Length and also counts bytes as it copies, because a chunked request has no length:
if (req.getContentLengthLong() > MAX_RAW) {
throw new ResponseStatusException(HttpStatus.CONTENT_TOO_LARGE, "Limit is " + MAX_RAW + " bytes");
}
// ...inside the copy loop:
total += n;
if (total > MAX_RAW) { out.close(); Files.delete(target); throw new ResponseStatusException(HttpStatus.CONTENT_TOO_LARGE, "Limit is " + MAX_RAW + " bytes"); }
With a 20MB limit, a 5MB body returned 200. A 50MB body returned 413 when curl had sent 917,504 bytes, because the length check fired first. A chunked 50MB body returned 413 after curl had sent 23,007,597 bytes, and the partial file was deleted. If the app runs in a container, uploadDir is inside that container's filesystem unless you mount a volume there, which dockerizing a Spring Boot application walks through.
[!TAKEAWAY] The ten-line upload works, and the defaults around it are where it breaks. The 1MB limit returns an empty 413 until you add a handler, and that handler catches three different causes under one message. The temp file is gone when your method returns.
getBytes()holds the whole file in memory.getOriginalFilename()andgetContentType()are just what the client said. Store under a name you generate, stream to an absolute path, and put your own limit on any raw body.
Frequently asked questions
- What is the default file upload size limit in Spring Boot?
- 1MB per file and 10MB for the whole request, set by spring.servlet.multipart.max-file-size and max-request-size. The limit is inclusive: a file of exactly 1,048,576 bytes was accepted and one byte more was rejected with HTTP 413. Tomcat also caps a multipart request at 50 parts, and exceeding that produces the same error.
- Why does my upload return 413 with an empty body?
- Spring resolves MaxUploadSizeExceededException to 413, then Tomcat forwards to /error to render a body. That forward re-parses the same oversized multipart request, fails again, and gives up with Content-Length: 0. The server log shows the WARN line twice for that reason. A @ControllerAdvice handler, or spring.mvc.problemdetails.enabled=true, gets a real body out.
- Can @ControllerAdvice catch MaxUploadSizeExceededException?
- Yes. The exception is thrown while the DispatcherServlet parses the request, before any controller is chosen, and a global @RestControllerAdvice still handles it. On Spring Boot 4.1.1 the handler returned a 413 application/problem+json body. Do not print getMaxUploadSize() in the message, though: it returned -1.
- Should I use getBytes() or transferTo() for large files?
- Stream it. getBytes() allocated 52,431,920 bytes for a 50MB file and 209,718,152 bytes for a 200MB one on the request thread, and in three runs of two concurrent 200MB uploads on a 256MB heap, one upload failed with OutOfMemoryError each time. transferTo(Path) and copying getInputStream() allocated under 10KB for the same files.
- Is getOriginalFilename() safe to use as the stored file name?
- No. It is exactly what the client sent. A filename of ../escaped.txt was returned unchanged and wrote a file one directory above the upload folder, and an absolute path replaced the folder entirely. Generate your own name, such as a UUID, and keep the original only as metadata.