Uploading files in Spring Boot can feel confusing at first — especially when you're dealing with images, documents, or multiple file uploads.
If you've ever struggled with handling file uploads in your backend application, you're not alone.
In this step-by-step guide, you'll learn how to upload single and multiple files in Spring Boot using a simple and clean approach. By the end of this tutorial, you'll be able to build real-world features like profile image upload, document submission, and more.
Learn how to handle file uploads in Spring Boot with real examples, best practices, and clean code
- Upload file API
- Save file to local folder
- Return file response
- Handle multiple file uploads
Technologies Used
- Java 8+
- Spring Boot
- Spring Web
- Multipart File
Step 1: Configure File Upload
Add this in application.properties:
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MBStep 2: Create Controller
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/file")
public class FileUploadController {
private final String UPLOAD_DIR = "uploads/";
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
File dir = new File(UPLOAD_DIR);
if (!dir.exists()) dir.mkdirs();
String filePath = UPLOAD_DIR + file.getOriginalFilename();
file.transferTo(new File(filePath));
return "File uploaded successfully: " + filePath;
} catch (IOException e) {
return "File upload failed: " + e.getMessage();
}
}
}API Testing
Endpoint
POST /file/upload
Form Data
Key: file
Type: File
Output
File uploaded successfully: uploads/sample.jpgStep 3: Upload Multiple Files
@PostMapping("/upload-multiple")
public String uploadMultiple(@RequestParam("files") MultipartFile[] files) {
for (MultipartFile file : files) {
try {
file.transferTo(new File("uploads/" + file.getOriginalFilename()));
} catch (IOException e) {
return "Error: " + e.getMessage();
}
}
return "All files uploaded successfully";
}Important Tips
- Validate file size
- Allow only specific file types
- Avoid duplicate file names
- Store files securely
Real-World Use Case
- Profile image upload
- Document submission
- Resume upload
- Product images
File upload is a must-have feature in most applications. Spring Boot makes it simple using MultipartFile.
With this setup, you can easily handle both single and multiple file uploads.
Try extending this by uploading files to cloud storage like AWS S3 or Google Cloud.
👉 Follow for more Spring Boot tutorials 🚀 👉 Available for freelance backend projects 💼