Introduction
In today’s digital age, file handling is a fundamental requirement in many web applications. Whether you’re building an application that needs to upload user-generated content, store documents, or allow users to download reports, having a reliable file management system is crucial.
In this blog, we’ll walk through the process of building a Spring Boot application that supports file uploads and downloads. You’ll learn how to set up a project, configure file storage, implement the necessary features, and even explore some best practices to make your file management system more secure and efficient.
Setting up the Spring Boot Project
Create a Spring Boot Project using Spring Initializer. Give details such as project, language, SpringBoot version and project metadata.
Below is the project hierarchy of our application. We are going to create below packages and classes as shown.
Let's understand the various Spring components like @RestController
, @Service
, and @Repository
. Here’s an explanation of each part:
SpringFileDemoApplication.java
Purpose: This is the main class that bootstraps the Spring Boot application. The @SpringBootApplication
annotation is a convenience annotation that adds:
@Configuration
: Tags the class as a source of bean definitions.@EnableAutoConfiguration
: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.@ComponentScan
: Tells Spring to look for other components, configurations, and services in the package.
FileController.java
Purpose: This class serves as the controller layer, handling HTTP requests related to file operations.
@RestController
: Indicates that this class handles RESTful web service requests.@RequestMapping("/files")
: Maps requests starting with/files
to this controller.
Endpoints:
@PostMapping("/upload")
: Handles file upload. Receives aMultipartFile
and calls the service layer to save it.@GetMapping("/download")
: Handles file download. Receives afileName
as a request parameter and returns the file as aResponseEntity<byte[]>
for downloading.
We can logger to track upload and download of the files.
FileData.java
Purpose: This class is an entity representing the file data stored in MongoDB.
@Document(collection = "files")
: Specifies that this class will be stored in a MongoDB collection namedfiles
.@Id
: Marks theid
field as the primary key.@Builder
,@NoArgsConstructor
,@AllArgsConstructor
,@Data
: Lombok annotations that generate boilerplate code like getters, setters, constructors, and the builder pattern.
Builder Pattern: The class manually implements the builder pattern, allowing for fluent creation of FileData
objects.
StorageService.java
Purpose: The StorageService
class you provided is a service layer in a Spring Boot application that handles file storage operations. It interacts with the StorageRepository
to perform CRUD operations on file data stored in a MongoDB database.
This performs two operations i.e upload and download.
File Upload Method
Purpose: This method handles the uploading of files.
Parameters:
MultipartFile file
: Represents the file that is being uploaded.
Steps:
Logging: Logs the start of the file upload process.
Builder Pattern: Uses the builder pattern to create a
FileData
object containing the file’s metadata (name, type) and the file's data in bytes.Saving to Repository: The constructed
FileData
object is saved to the MongoDB database using therepository.save
(fileData)
method.Logging Success: Logs a success message once the file is uploaded.
Return Statement: Returns a confirmation message with the file name.
File Download Method:
Purpose: This method retrieves a file from the database based on its name.
Parameters:
String fileName
: The name of the file to be downloaded.
Interface StorageRepository
Purpose: This is the repository interface that provides CRUD operations for FileData
.
MongoRepository<FileData, String>
: Extends Spring Data’sMongoRepository
to provide standard database operations.findByName
: A custom query method that retrieves aFileData
object by its name.
If you are new to MongoDB, here are some basic steps to connect MongoDB from SpringBoot Application.
Step 1: Create new project -> click on project
Step 2: Click on connect section
Step 3: It will show below option depending upon requirement we have to choose option. As we are using for SpringBoot application select Drivers field.
Step 4: As shown in below screenshot provide details such as project tech stack for e.g. Java and it's version. Copy that DB URL string and paste into application.properties
Replace username and password of respective database.
Step 5: Whitelist your local Desktop/Server IP. So that MongoDB should allow only authorised users.
Now, we have completed all coding and configuration part. Let's start our application.
As shown above, SpringBoot will start it's services on 8084 and it will load MongoDB driver. It shows that it is able to connect MongoDB database successfully.
We can verify application process by checking it's process and port
Now let's try to upload our sample file.
To upload file in MongoDB
curl -X POST -F "file=@/home/sandeep/Documents/Doc/README.md" http://localhost:8084/files/upload
To download file from MongoDB
curl -O http://localhost:8084/files/download/README.md
In the below screenshot as we can see file uploaded in MongoDB database successfully and we can retrieve as well.
Thank you for reading...