Handling File Upload and Download with Spring Boot REST

In many web applications, file handling is a common requirement β€” whether it’s uploading profile pictures, downloading reports, or exporting data. Spring Boot makes it easy to build robust REST APIs that support file upload and download using standard HTTP protocols.

In this guide, we’ll build:

  • A REST API to upload files using MultipartFile
  • A REST API to download files from the server
  • Simple validations and content-type handling
Handling File Upload and Download with Spring Boot REST

βš™οΈ Project Setup

Dependencies:



    org.springframework.boot
    spring-boot-starter-web


πŸ“ Directory Structure:


src/main/java
└── com.kscodes.fileapi
    β”œβ”€β”€ controller
    β”œβ”€β”€ service
    └── model

⬆️ File Upload REST API

βœ… Create Upload Controller


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

    private final String uploadDir = "uploads/";

    @PostMapping("/upload")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            Path path = Paths.get(uploadDir + file.getOriginalFilename());
            Files.createDirectories(path.getParent());
            Files.write(path, file.getBytes());
            return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to upload file");
        }
    }
}

πŸ”’ Add Validation (Optional)


if (file.isEmpty()) {
    return ResponseEntity.badRequest().body("File is empty");
}

if (!file.getContentType().equals("application/pdf")) {
    return ResponseEntity.badRequest().body("Only PDF files are allowed");
}

⬇️ File Download REST API

βœ… Add Download Controller


@GetMapping("/download/{filename}")
public ResponseEntity downloadFile(@PathVariable String filename) {
    try {
        Path path = Paths.get(uploadDir + filename);
        Resource resource = new UrlResource(path.toUri());

        if (resource.exists()) {
            String contentType = Files.probeContentType(path);
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    } catch (IOException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

πŸ§ͺ Testing the APIs

βœ… Upload File using Postman

  • Method: POST
  • URL: http://localhost:8080/api/files/upload
  • Body: Form-data with key file and attach any file

βœ… Download File

  • Method: GET
  • URL: http://localhost:8080/api/files/download/filename.txt
  • Response: Prompts file download

🧠 Best Practices

Best PracticeDescription
βœ… Limit file sizeConfigure spring.servlet.multipart.max-file-size=5MB
βœ… Sanitize filenamePrevent path traversal with filename.replaceAll("[^a-zA-Z0-9\\.\\-]", "_")
βœ… Store in DB or CloudFor large-scale apps, consider storing file metadata in a DB and files in cloud (e.g., S3)
βœ… Secure endpointsProtect upload/download routes using Spring Security
βœ… Return custom responsesUse custom DTOs for better client experience

βš™οΈ Optional: application.properties


spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB

πŸ“ Upload Directory Setup (Optional)

Ensure the directory exists or create one programmatically:


@PostConstruct
public void init() {
    new File("uploads").mkdirs();
}

βœ… Conclusion

Handling file upload and download in Spring Boot is simple with MultipartFile and ResponseEntity. With proper error handling, validation, and security, you can build production-ready APIs for file management quickly.

Reference

Upload Docs