Spring Boot REST API : Upload & Download files

📦 Tech Stack

  • Spring Boot
  • Spring Web (REST)
  • Multipart support (MultipartFile)
  • File System for storage

📁 1. Maven Dependencies (pom.xml)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

🛠️ 2. Controller Class – File Upload & Download

@RestController
@RequestMapping("/api/files")
public class FileController {

    private static final String UPLOAD_DIR = "uploads/";

    // Handle file upload
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) Files.createDirectories(uploadPath);

            Path filePath = uploadPath.resolve(file.getOriginalFilename());
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body("Error uploading file: " + e.getMessage());
        }
    }

    // Handle file download
    @GetMapping("/download/{filename}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }

        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        }
    }
}


📂 3. Create Upload Directory

Manually create a folder in your project root:

/your-project
  └── uploads/

Or ensure the controller creates it dynamically, as shown.


🔄 4. Test with Postman or Curl

Upload a File:

  • Method: POST
  • URL: http://localhost:8080/api/files/upload
  • Form-Data: Key = file, Value = your file

Download a File:

  • Method: GET
  • URL: http://localhost:8080/api/files/download/sample.txt

✅ Bonus: Return JSON Metadata

You can also return file size, content-type, or saved path in the response instead of a simple string.

Back to blog

Leave a comment