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:

📁 Directory Structure:

⬆️ File Upload REST API

✅ Create Upload Controller

🔒 Add Validation (Optional)

⬇️ File Download REST API

✅ Add Download Controller

🧪 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

📁 Upload Directory Setup (Optional)

Ensure the directory exists or create one programmatically:

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