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: • The controller method parameter is annotated @RequestParam with a name matching the HTML file input's name attribute. • The HTML form must declare enctype="multipart/form-data", otherwise the file bytes never reach the server as a multipart body. • Before saving, it's good practice to check file.isEmpty(), validate the content type, and enforce a maximum size. • file.transferTo(File) writes the upload to disk, while file.getBytes() gives in-memory access for processing before persisting elsewhere, like cloud storage. • Returning a clear error response for invalid uploads (wrong type, too large) is better UX than letting an exception propagate.
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.
Code Example:
@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."