SpringData MongoDB GridFsTemplate to save, retrieve, delete binary files (Image, Text files)

MongoDB provides GridFS for storing and retrieving large files with size limit of 16MB. So in the tutorial, JavaSampleApproach will show you how to work with SpringData Mongo GridFsTemplate to save, retrieve, delete binary files (Image, Text files).

Related posts:
How to use SpringData MongoRepository to interact with MongoDB
Spring MongoOperations to access MongoDB
MongoDB – Model One-to-One, One-to-Many Relationships Embedded Documents | SpringBoot

I. Technologies

– Java: 1.8
– Maven: 3.3.9
– Spring Tool Suite: Version 3.8.4.RELEASE
– Spring Boot: 1.5.7.RELEASE
– MongoDB: version v3.4.9

II. SpringData Mongo GridFsTemplate

SpringData MongoDb provides GridFsTemplate class to work with GridFs file, details:

GridFsTemplate implement interface GridFsOperations that is the collection of operations to store and read files from MongoDB GridFS.

For convenient working, SpringBoot provides spring-boot-starter-data-mongodb dependency that is the collection of {mongodb-driver, spring-data-mongodb}.

III. Practice

In the tutorial, we create a SpringBoot project as below:

SpringData Mongo GridFs - project structure

Step to do:
– Create SpringBoot project
– Configure GridFsTemplate
– Implement RestAPIs to work with GridFs files
– Run & check results

1. Create SpringBoot project

Using SpringToolSuite, create a SpringBoot project, then add dependencies:

2. Configure GridFsTemplate

Using AbstractMongoConfiguration to configure GridFsTemplate:

Open application.properties file, add configuration:

3. Implement RestAPIs to work with GridFs files

Using GridFsOperations to implement 4 RestfulAPIs {/api/save, /api/retrieve/imagefile, /api/retrieve/textfiles, /api/delete/image}:

4. Run & check results

Build and Run the SpringBoot project with commandlines: {mvn clean install, mvn spring-boot:run}.

– Make a saving request: http://localhost:8080/api/save

SpringData Mongo GridFs - save results

– Make a retrieving image request: http://localhost:8080/api/retrieve/imagefile

SpringData Mongo GridFs - retrieve image file

– Make a retrieving textfiles request: http://localhost:8080/api/retrieve/textfiles

SpringData Mongo GridFs - retrieve text files

– Make a delete request: http://localhost:8080/api/delete/image

SpringData Mongo GridFs - after delete

IV. Sourcecode

SpringDataGridFsTemplate


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*