Category: java
file download in spring boot
Published on 26 May 2026
Explanation
Spring Boot allows downloading files using
ResponseEntity and Resource classes.
Code:
@GetMapping("/download")
public ResponseEntity<Resource>
downloadFile() {
return null;
}
Explanation
Read a file from local storage
using UrlResource.
Code:
Path path = Paths.get("uploads/sample.pdf");
Resource resource =
new UrlResource(path.toUri());
Explanation
Return the file as a downloadable
response with proper headers.
@GetMapping("/download")
public ResponseEntity<Resource>
downloadFile() throws Exception
{
//code
}
Code:
Path path = Paths.get("uploads/sample.pdf");
Resource resource = new UrlResource(
path.toUri());
return ResponseEntity.ok()
.header(
HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=sample.pdf")
.contentType(
MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
Explanation
Browser automatically downloads the file
when
Content-Disposition is set to attachment.
Code:
Content-Disposition: attachment; filename=sample.pdf
Explanation
Complete flow: Client requests file ->
Spring Boot reads file -> ResponseEntity
sends file -> Browser downloads it.
Code:
Client --> Spring Boot API --> Read File --> ResponseEntity<Resource> --> File Download