FileUploadDownloadPoc is a Spring Boot application that demonstrates storing and retrieving files using an H2 Database. This is a Proof of Concept (PoC) and is not intended for production use.
- File Upload: Upload files (images, PDFs, Word documents) directly to the H2 database.
- File Retrieval: Retrieve files using a file ID.
- Spring Boot & H2 Integration: Uses an in-memory H2 database for temporary storage.
Storing files (binary data) directly in a relational database is not a best practice, especially for high-traffic applications. Here’s why:
- Performance Issues: Databases are optimized for structured data, not large binary objects.
- Increased DB Load: Large files increase database size, slowing down queries and backups.
- Scaling Issues: Harder to distribute files across multiple servers efficiently.
- Only recommended for low-traffic applications or small-scale proof of concepts.
- Store files in a server’s file system and save the file path in the database.
- Use cloud storage buckets (Recommended for scalability and reliability), e.g., AWS S3, Google Cloud Storage, or Azure Blob Storage.
| Method | Endpoint | Description |
|---|---|---|
| POST | /upload |
Upload a file |
| GET | /download/{id} |
Retrieve a file by ID |
- Spring Boot
- H2 Database (In-Memory for PoC)
- Spring Data JPA
When serving a file in a Spring Boot application, you can control how the browser handles it using the Content-Disposition header.
You can set Content-Disposition
@GetMapping("/download/{id}")
public ResponseEntity<byte[]> downloadFile(@PathVariable Long id){
FileEntity file = fileService.getFileById(id);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(file.getFileType()));
headers.setContentDisposition(ContentDisposition.builder("inline")
.filename(file.getFileName())
.build());
return ResponseEntity.ok()
.headers(headers)
.body(file.getData());
}Content-Disposition: inline; filename="document.pdf"- The browser tries to display the file instead of downloading it.
- Works well for images (
.jpg,.png), PDFs (.pdf), and text files (.txt). - Example: If you request a PDF with
inline, the browser opens it in the built-in PDF viewer.
Content-Disposition: attachment; filename="document.pdf"- Forces the browser to prompt for download instead of displaying it.
- Works for all file types.
- Example: When clicking a download link, the browser asks, "Do you want to save this file?"
when uploading a file in a Spring Boot REST API, you typically use @RequestParam instead of @RequestBody because:
Serialization Limitation: Files (binary data) cannot be directly serialized into JSON or other text-based formats used in @RequestBody.
Multipart Form Data: File uploads require multipart/form-data encoding, which @RequestParam supports.
Spring Support: Spring provides built-in support for handling file uploads using MultipartFile, which works seamlessly with @RequestParam.



