File Upload and Download in Spring Boot
Handling file upload and download is a common requirement in many web applications. Whether it's profile pictures, reports, or documents, Spring Boot makes file handling straightforward with powerful APIs and easy configuration.
✅ Setting Up Spring Boot Project
To get started, create a Spring Boot application with the following dependencies:
Spring Web
Spring Boot DevTools (optional)
Spring Boot Starter Thymeleaf (if using frontend templating)
Also, ensure you configure the file storage path in application.properties:
properties
file.upload-dir=uploads/
📤 File Upload Implementation
Create a REST controller for handling file uploads:
@RestController
@RequestMapping("/files")
public class FileController {
private final Path root = Paths.get("uploads");
@PostMapping("/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
try {
Files.copy(file.getInputStream(), this.root.resolve(file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body("File upload failed");
}
}
}
Make sure to configure a MultipartResolver bean if not using Spring Boot’s auto-configuration.
📥 File Download Implementation
Add the download functionality to the same controller:
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> download(@PathVariable String filename) throws IOException {
Path file = root.resolve(filename);
Resource resource = new UrlResource(file.toUri());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
🛡️ Security & Best Practices
✅ Validate file types and size.
✅ Store files outside the project directory for safety.
✅ Avoid overwriting by renaming files with UUIDs or timestamps.
✅ Limit public access to download endpoints if dealing with sensitive data.
📌 Conclusion
Spring Boot simplifies the implementation of file upload and download functionality through its robust web and file handling APIs. With minimal code and configuration, developers can integrate this essential feature into their applications quickly and securely.
From simple document storage to complex file management systems, mastering file operations in Spring Boot is a valuable skill for any backend developer.
Learn MERN Stack Training Course
Managing State with useState Hook
Understanding the useEffect Hook
JWT Authentication in Spring Boot
Visit Our Quality Thought Training Institute
Comments
Post a Comment