๐Ÿ“ฆ What is MultipartFile?

MultipartFile is an interface provided by Spring to represent an uploaded file received in a multipart/form-data request.

It allows you to read, store, or manipulate uploaded files in memory or on disk.

๐Ÿ”ง It lives in: org.springframework.web.multipart.MultipartFile


๐Ÿงช Common Use Case

File upload in a REST API:

@PostMapping("/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
ย  ย  // Logic to store file
}

โœ… Automatically maps uploaded file to the MultipartFile parameter.


๐ŸŽฏ Key Methods in MultipartFile

Method Description
getName() Returns the name of the parameter in the form
getOriginalFilename() Gets the original filename (e.g., "resume.pdf")
getContentType() MIME type like "image/png", "application/pdf"
getBytes() File content as byte array
getInputStream() InputStream to read file content
transferTo(File dest) Save uploaded file to a specific location
isEmpty() Checks if the file has no content

๐Ÿ› ๏ธ Sample File Upload Endpoint

@RestController
public class FileUploadController {

ย  ย  @PostMapping("/upload")
ย  ย  public String uploadFile(@RequestParam("file") MultipartFile file) {
ย  ย  ย  ย  try {
ย  ย  ย  ย  ย  ย  File dest = new File("uploads/" + file.getOriginalFilename());
ย  ย  ย  ย  ย  ย  file.transferTo(dest); // saves file to disk
ย  ย  ย  ย  ย  ย  return "Uploaded: " + file.getOriginalFilename();
ย  ย  ย  ย  } catch (IOException e) {
ย  ย  ย  ย  ย  ย  return "Upload failed: " + e.getMessage();
ย  ย  ย  ย  }
ย  ย  }
}


๐Ÿ“‚ Multipart Configuration (Optional)

Spring Boot automatically enables multipart support, but you can configure limits:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=15MB

๐Ÿง  Notes

  • @RequestParam("file") MultipartFile file binds the form field named "file" to the parameter.
  • Can support multiple files using MultipartFile[] or List<MultipartFile>.
  • Make sure your frontend uses enctype="multipart/form-data".

โœ… Summary

Feature Description
Interface Name MultipartFile
Used For Handling file uploads in Spring Boot
Key Methods getBytes(), getOriginalFilename(), transferTo()
Configuration Set max sizes in application.properties
Back to blog

Leave a comment