File Upload/Download with SpringBoot and MongoDB

Hansani Tharaka
Nerd For Tech
Published in
4 min readJun 1, 2021

--

File upload & Download with spring boot and mongoDB article cover

In this article, we will be creating a simple RESTful web service using SpringBoot and MongoDB. We will be using GridFS to store files.

What is GridFS?

GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16MB. (Source: MongoDB Manual)

GridFS divide the file into small parts called chunks and store them as separate documents. The default size of a chunk is 255KB.

GridFS uses two collections to store files.

  • fs.files - store file’s metadata.
  • fs.chunks - store binary chunks of the file.
How GridFS works

We’ll start by creating the REST APIs for uploading and downloading and test them using Postman. Alright! Let’s get to it.

1. Creating a project

Visit https://start.spring.io to generate the application through Spring Initializr with the following dependencies. This should download a zip file which you need to extract and open in your IDE.

Spring Initializr to create a maven project

2. Spring Boot Properties

Following configurations must be provided in the application.properties file in the “resources” folder.

Following are the MongoDB properties:

spring.data.mongodb.port = 27017
spring.data.mongodb.host = localhost
spring.data.mongodb.database = uploads

server.port=8080

The default port for service is 8080. You can change the port if you want. Also You can add authentication if you have any.

You can also use MongoDB Atlas instead of running MongoDB on localhost. Use the following properties in your application.

Replace <passsword> with admin’s password and <database> with the database name.

spring.data.mongodb.uri=mongodb+srv://admin:<password>@cluster0.eypdh.mongodb.net/<database>?retryWrites=true&w=majority

In addition, the following properties should be added to allow file uploading.

spring.servlet.multipart.enabled = true
spring.servlet.multipart.max-file-size = 200MB
spring.servlet.multipart.max-request-size = 200MB

3. Defining Classes

Note that we are not defining a document class here since we will only upload a file and it will directly store in the GridFS Collection.

The following class will be used to return the necessary responses when downloading a file.

4. Creating the Service Class

This service class contains the service to store and retrieve a file from GridFS.

Storing a file

  • addFile() method will store the file in the database and returns the Object ID of the file.
  • You can add extra information to your file as metadata. As an example, I have added file size as additional information. But it is not a must.
  • To store the file you need to pass the following data to the store method in GridFsTemplate.
template.store(Inputstream content, filename, ContentType, metadata)

Retrieving a file

  • downloadFile() method is used to return a specific file from the database.
  • findOne method in GridFSTemplate will return the file that matches the query.
  • Then, we set the response and its content to an Object from LoadFile class we created in Step 1 and return it.
  • We need to set the file to a byte array. To convert the InputStream into a byte array we are using Apache Commons IO.
  • For that, you need to add the following dependency in your pom.xml file.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>

5. Creating the Controller

The controller class consist of the REST APIs for uploading and downloading a file.

POST

  • To upload a file we use the POST method.
  • The upload() method accepts a MultipartFile type object here.

GET

  • The GET method takes the {id} as a path parameter to return a specific document.
  • By download() method, receive the LoadFile object first, and then map the necessary details to a Response Header to make it downloadable.

Note that we are returning the data as a ByteArrayResource.

6. Testing REST end-points via Postman

Once you run the application, it can be accessed at http://localhost:8080

# Upload File

Here we are testing POST method via Postman to see if the file is uploading.
Representation of how a file is saved in fs.files collection. Here include all the metadata of the file.
fs.files collection with uploaded file’s metadata
Representation of how chunks are saved in fs.chunks collection. The uploaded file will be divided into several chunks and stored in fs.chunks collection.
The uploaded file will be divided into several chunks and stored in fs.chunks collection

# Download File

Here we are testing the GET method via Postman to see if the file is retrieving.

7. Developing the FrontEnd

Now that we have finished our backend and it is working smoothly, let’s add a frontend. 😃

I have included all the frontend files in the src/main/resources/static folder.

# index.html

# main.css

Let’s add some CSS to make it look less boring. 😅

# main.js

To make everything work, let’s add a bit of javascript.

Conclusion

I came across this topic when I was developing a web application for my 3rd-year project and I was struggling to find the right resources.

So, I hope this tutorial was helpful for you. 😊

Also, you can download this project from my GitHub repo here.

Check out these links to learn more about GridFS.

Until next time, Keep exploring !!! 🤓💪

--

--

Hansani Tharaka
Nerd For Tech

Assoiciate Software Enginner | UI/UX | Developer