Hackforge Academy

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);
}

๐Ÿš€ 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