Hackforge Academy

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

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community