Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a Spring MVC endpoint that accepts a file upload plus a JSON metadata part, and explain the default size limits in Spring Boot.

We write a @PostMapping that consumes multipart/form-data and takes @RequestPart("file") MultipartFile file and @RequestPart("meta") MetaDto meta, where the meta part is sent with Content-Type application/json so Jackson can convert it. Spring Boot limits uploads by default to 1MB per file (spring.servlet.multipart.max-file-size) and 10MB per request (max-request-size); going over raises MaxUploadSizeExceededException, which we map to 413. For large files we stream with transferTo or getInputStream instead of getBytes, and we never trust the client's filename or content type.

Why this question is asked

File uploads look like a small feature, but they hide several traps: the defaults are tiny, so the first real user with a 5 MB PDF gets an unexplained error; reading the file into a byte array can exhaust the heap; and the filename and content type come straight from the client, so they can be used for attacks. Interviewers ask this question to see whether we can write the endpoint correctly and also know these edges. In this answer, we will recap how multipart requests are structured, write the endpoint, call it with curl, look at the size limits and the 413 mapping, store the file without loading it into memory, and handle names and content safely.

1A Quick Recap of Multipart Requests

A normal JSON request has one body with one content type. A multipart/form-data request has a body split into parts, separated by a boundary string that the client chooses. Each part has its own small set of headers, such as Content-Disposition with a name, an optional filename, and its own Content-Type. That is how one request can carry a binary file and a JSON document side by side.

On the server, the servlet container (Tomcat in a default Spring Boot application) parses the parts. Spring wraps each file part as a MultipartFile, and for other parts it can run the usual message converters. @RequestPart is the annotation that binds one named part to a parameter: for a file it gives a MultipartFile, and for a JSON part it uses Jackson to turn the part's body into our DTO, just like @RequestBody does for a whole request.

One upload request, two parts
Part namePart headersBound as
filefilename="scan.pdf", Content-Type: application/pdfMultipartFile file
metaContent-Type: application/jsonMetaDto meta (via Jackson)
Each part carries its own headers; the meta part needs application/json to be converted.

2Writing the Endpoint

Here is the controller. The metadata is a record, and we validate it with @Valid like any other request body.

Java
public record MetaDto(@NotBlank String title, @Size(max = 500) String description) {}
@RestController
@RequestMapping("/documents")
class DocumentController {
private final DocumentStorage storage;
DocumentController(DocumentStorage storage) { this.storage = storage; }
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<DocumentView> upload(@RequestPart("file") MultipartFile file,
@Valid @RequestPart("meta") MetaDto meta) throws IOException {
if (file.isEmpty()) {
return ResponseEntity.badRequest().build(); // 400: empty part
}
DocumentView saved = storage.store(file, meta);
return ResponseEntity.status(HttpStatus.CREATED).body(saved); // 201
}
}

The consumes attribute makes Spring route only multipart requests here, so a JSON-only request gets 415 Unsupported Media Type instead of a confusing binding error. Notice that the part names in the annotations must match the names the client uses. A missing part produces MissingServletRequestPartException, which Spring turns into 400.

3Calling It and the Content-Type Trap

The most common bug with this endpoint is on the client side. If the meta part is sent as a plain form field, its content type is missing or text/plain, and Spring cannot pick the JSON converter. With curl, we set the type of that part explicitly.

Shell
curl -X POST http://localhost:8080/documents \
-F "file=@scan.pdf;type=application/pdf" \
-F 'meta={"title":"Contract","description":"Signed copy"};type=application/json'
# HTTP/1.1 201 Created
# without ";type=application/json" on meta:
# HTTP/1.1 415 Unsupported Media Type (no converter for text/plain to MetaDto)

In a browser, the same applies: we append the JSON as a Blob with type application/json to the FormData, not as a string. Once the part types are right, the binding is as simple as the controller suggests.

4The Default Size Limits and Mapping Them to 413

Spring Boot configures multipart handling with two limits by default. spring.servlet.multipart.max-file-size is 1MB, the largest single file, and spring.servlet.multipart.max-request-size is 10MB, the whole request with all parts. Those defaults protect a new application from accidental huge uploads, but they are too small for most real document features, so we set them deliberately.

When a request goes over a limit, parsing fails before our controller runs and Spring raises MaxUploadSizeExceededException. Left alone, it becomes a generic error. The correct status is 413 Content Too Large (historically called Payload Too Large), so we map it in a controller advice.

Java
# application.properties
spring.servlet.multipart.max-file-size=25MB
spring.servlet.multipart.max-request-size=30MB
@RestControllerAdvice
class UploadErrors {
@ExceptionHandler(MaxUploadSizeExceededException.class)
ProblemDetail tooLarge(MaxUploadSizeExceededException e) {
ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.PAYLOAD_TOO_LARGE); // 413
pd.setDetail("Files may be at most 25 MB");
return pd;
}
}

But there is a catch with very large bodies. Tomcat stops reading a rejected body after a limit of its own (maxSwallowSize, 2MB by default; check your version), and then closes the connection, so a client sending 500 MB may see a connection reset rather than our 413. Limits in the load balancer or proxy, such as an nginx client_max_body_size, also apply before the request ever reaches Spring, so all three layers must agree.

5Storing the File Without Loading It Into Memory

MultipartFile offers getBytes(), and it is tempting to call it. For a 25 MB file it allocates a 25 MB array on the heap, and ten parallel uploads take 250 MB. The container has already put the upload into a temporary file on disk (the spring.servlet.multipart.file-size-threshold default of 0B means every file part goes to disk), so the efficient path is to move or copy that file rather than read it.

Java
// risky for large files
byte[] all = file.getBytes(); // whole file on the heap
// better: copy the stream to its destination in small chunks
Path target = baseDir.resolve(UUID.randomUUID() + ".pdf");
file.transferTo(target); // moves or copies the temp file
// or stream to object storage
try (InputStream in = file.getInputStream()) {
objectStore.put(key, in, file.getSize()); // read in buffers, never all at once
}

transferTo is the simplest when the destination is local disk; getInputStream lets us stream to object storage or a checksum calculation with constant memory.

6Never Trusting the Filename and Content Type

getOriginalFilename() and getContentType() are just text the client wrote into the part headers. An attacker can send a filename of ../../etc/cron.d/job or a content type of image/png on an HTML file. So we treat both as untrusted input.

For storage we generate our own name, a UUID, and keep the original name only as metadata in the database after cleaning it: take only the last path segment, drop control characters and limit the length. For content, we check what the bytes really are, for example by reading the first bytes (the magic number, such as %PDF- for PDF files) or with a library like Apache Tika, and compare that against an allow list of types the feature accepts. Only then do we store it, and when we serve it back we use the type we detected, not the one the client claimed.

7Follow-up questions

How do you prevent path traversal when saving the original filename?

The safest answer is not to use it in the path at all: store the file under a generated key such as a UUID and keep the original name only as a database column. If a name must be used, take Paths.get(name).getFileName() to drop directories, reject names with .. or control characters, resolve it against the base directory, call normalize(), and check that the result still startsWith the base directory before writing. Anything outside is rejected with 400.

Why does my endpoint return 415 when I send the JSON part?

Because the meta part arrived without Content-Type application/json, so Spring has no converter that turns text/plain into MetaDto. Set the part's type explicitly, with ;type=application/json in curl or a Blob of type application/json in browser FormData.

Where are the uploaded bytes held before the controller runs?

The servlet container parses the request and writes file parts to a temporary location, or keeps small ones in memory when a file-size-threshold above zero is configured. Spring deletes those temporary files after the request, so we must move or copy the file during the request, not keep the MultipartFile for later.

8Conclusion

In this answer, we wrote a multipart endpoint with @PostMapping(consumes = multipart/form-data), a MultipartFile bound with @RequestPart("file") and a JSON DTO bound with @RequestPart("meta"), and saw that the meta part must carry application/json. We looked at Spring Boot's defaults of 1MB per file and 10MB per request, mapped MaxUploadSizeExceededException to 413, and noted that Tomcat and proxies have limits of their own. Finally, we stored files with transferTo or streams instead of getBytes, and treated the client's filename and content type as untrusted input.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write a controller method with @PostMapping and consumes set to MediaType.MULTIPART_FORM_DATA_VALUE, taking @RequestPart("file") MultipartFile file and @Valid @RequestPart("meta") MetaDto meta. RequestPart runs the normal message converters for the JSON part, so the client has to send that part with Content-Type application/json, otherwise it gets a 415.

Then, if they want more

For limits, Spring Boot defaults to 1MB per file with spring.servlet.multipart.max-file-size and 10MB per request with max-request-size, which is usually too small, so I set them explicitly. If a request exceeds them, parsing fails before the controller and Spring throws MaxUploadSizeExceededException, which I map to 413 in a RestControllerAdvice, returning a ProblemDetail.

I would also mention that Tomcat and the load balancer have their own body limits, so all layers need to agree. For storage I avoid getBytes because it puts the whole file on the heap; I use transferTo to a path or stream getInputStream to object storage, which keeps memory constant.

And I never trust the original filename or content type: I store under a generated UUID, keep the cleaned original name only as metadata, which also prevents path traversal, and I check the real file type from its bytes against an allow list.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a Spring MVC endpoint that accepts a file upload plus a JSON metadata part, and...": https://scrivio-interview-library.netlify.app/spring-boot/web-other/568d51bf00/