Category: spring_boot
File Upload
Published on 26 Jun 2026
Explanation
File Upload APIs allow clients to
send files such as images, PDFs,
or documents to the server. In
Spring Boot, the MultipartFile interface is
used to receive uploaded files from
HTTP requests.
Code:
@PostMapping("/upload")
public String uploadFile(@
RequestParam("file") MultipartFile file) {
return file.getOriginalFilename();
}
Explanation
The MultipartFile object provides methods to
access file details such as file
name, content type, size, and file
bytes. These details are useful for
validation and processing.
Code:
@PostMapping("/upload")
public String uploadFile(
@RequestParam MultipartFile file) {
return "File Name: " +
file.getOriginalFilename() +
", Size: " + file.getSize();
}
Explanation
Uploaded files can be stored on
the server using the transferTo() method.
This method copies the uploaded file
to a specified location in the
file system.
Code:
@PostMapping("/upload")
public String uploadFile(
@RequestParam MultipartFile file)
throws IOException {
File destination =
new File("uploads/" +
file.getOriginalFilename());
file.transferTo(destination);
return "File uploaded successfully";
}
Explanation
File Download APIs allow clients to
retrieve files from the server. Spring
Boot can return a file as
a Resource object wrapped inside a
ResponseEntity.
Code:
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource>
downloadFile(
@PathVariable String fileName)
throws IOException {
Path path = Paths.get("uploads/" +
fileName);
Resource resource =
new UrlResource(path.toUri());
return ResponseEntity.ok().
body(resource);
}
Explanation
Response headers can be added during
file download to force browsers to
download the file instead of displaying
it. The Content-Disposition
header is commonly
used for this purpose.
Code:
Resource resource = new UrlResource(
Paths.get("uploads/" + fileName).
toUri()
);
return ResponseEntity.ok()
.header(HttpHeaders.
CONTENT_DISPOSITION,
"attachment;
filename=" + fileName)
.body(resource);
}