How do you handle a file upload in a Spring MVC controller?

Handling a file upload inside a controller means declaring a MultipartFile parameter bound to the uploaded input, then using that object to validate, inspect, and persist the file's contents.

Key Points

Example

A document upload controller might accept a MultipartFile named "document", reject anything that isn't a PDF by checking getContentType(), and otherwise stream it to an S3 bucket or a local uploads directory.

@PostMapping("/documents")
public ResponseEntity<String> uploadDocument(@RequestParam("document") MultipartFile file) {
    if (file.isEmpty() || !"application/pdf".equals(file.getContentType())) {
        return ResponseEntity.badRequest().body("Invalid file");
    }
    documentService.store(file);
    return ResponseEntity.ok("Uploaded");
}

Interview Tip

A concise interview answer is

In the controller I bind the uploaded file to a MultipartFile parameter with @RequestParam, matching the form's input name and requiring multipart/form-data encoding. Before persisting it I validate the file isn't empty and is the expected type, then use transferTo() or getBytes() to actually store it.

Last updated: 11 November 2026

Previous question: What configurations are needed to enable file uploads in a Spring MVC application?

Next question: What are common issues with file uploads in Spring MVC, and how do you solve them?

More Spring MVC (Optional) interview questions

All Spring MVC (Optional) questions