๐ฆ 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:
โ 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:
๐ง Notes
-
@RequestParam("file") MultipartFile file
binds the form field named"file"
to the parameter. - Can support multiple files using
MultipartFile[]
orList<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
|