Spring Data MongoDB : Save binary file, GridFS example

binary-data-flow

In MongoDB, you can use GridFS to store binary files. In this tutorial, we show you how to use Spring Data’s GridFsTemplate to store / read image in / from MongoDB.

1. GridFS – Save example (Spring config in Annotation)

Gat an image file and save it into MongoDB.

SpringMongoConfig.java

package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

/**
 * Spring MongoDB configuration file
 * 
 */
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration{
	
	@Bean
	public GridFsTemplate gridFsTemplate() throws Exception {
		return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
	}

	@Override
	protected String getDatabaseName() {
		return "yourdb";
	}

	@Override
	@Bean
	public Mongo mongo() throws Exception {
		return new MongoClient("127.0.0.1");
	}

}
GridFsAppStore.java

package com.mkyong.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.gridfs.GridFsOperations;

import com.mkyong.config.SpringMongoConfig;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * GridFs example
 * 
 * @author mkyong
 * 
 */

public class GridFsAppStore {

    public static void main(String[] args) {

	ApplicationContext ctx = 
                     new AnnotationConfigApplicationContext(SpringMongoConfig.class);
	GridFsOperations gridOperations = 
                      (GridFsOperations) ctx.getBean("gridFsTemplate");

	DBObject metaData = new BasicDBObject();
	metaData.put("extra1", "anything 1");
	metaData.put("extra2", "anything 2");

	InputStream inputStream = null;
	try {
		inputStream = new FileInputStream("/Users/mkyong/Downloads/testing.png");
		gridOperations.store(inputStream, "testing.png", "image/png", metaData);

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

		System.out.println("Done");
    }

}

Review the MongoDB console, see what is saved.


> show dbs
yourdb	0.203125GB

> use yourdb
switched to db yourdb

> show collections
fs.chunks
fs.files
system.indexes

> db.fs.files.find()
{ "_id" : ObjectId("51641c5630045c9b3db35afc"), "chunkSize" : NumberLong(262144), 
"length" : NumberLong(4238), "md5" : "9969527cd95a5a573f15e953f0036800", "filename" : "testing.png", 
"contentType" : "image/png", "uploadDate" : ISODate("2013-04-09T13:49:10.104Z"), 
"aliases" : null, "metadata" : { "extra1" : "anything 1", "extra2" : "anything 2" } }
>

> db.fs.chunks.find()
{ "_id" : ObjectId("51641c5630045c9b3db35afd"), 
"files_id" : ObjectId("51641c5630045c9b3db35afc"), "n" : 0, 
"data" : BinData(0,"/9j/4AAQSkZJRgABAgAAZ......EQH/9k=") }

The image’s information is saved in fs.files, and the image’s file (converted in binary) is stored in fs.chunks, and link via _id and files_id.

2. GridFS – Read example (Spring config in XML file)

Read above image file from MongoDB and save it as another image.

SpringConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/data/mongo 
       http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd">

	<mongo:db-factory id="mongoDbFactory" dbname="yourdb" />
	<mongo:mapping-converter id="converter" />

	<bean name="gridFsTemplate"
		class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
		<constructor-arg ref="mongoDbFactory" />
		<constructor-arg ref="converter" />
	</bean>

</beans>
GridFsAppStore.java

package com.mkyong.core;

import java.io.IOException;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;

/**
 * GridFs example
 * 
 * @author mkyong
 * 
 */

public class GridFsAppRead {

    public static void main(String[] args) {

	ApplicationContext ctx = 
              new GenericXmlApplicationContext("SpringConfig.xml");
	GridFsOperations gridOperations = 
              (GridFsOperations) ctx.getBean("gridFsTemplate");

	List<GridFSDBFile> result = gridOperations.find(
               new Query().addCriteria(Criteria.where("filename").is("testing.png")));

	for (GridFSDBFile file : result) {
		try {
			System.out.println(file.getFilename());
			System.out.println(file.getContentType());
				
			//save as another image
			file.writeTo("/Users/mkyong/Downloads/new-testing.png");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	System.out.println("Done");

    }
}

Download Source Code

Download it – SpringMongoDB-GridFs-Example.zip (24 KB)

References

  1. AbstractMongoConfiguration JavaDoc
  2. Spring Data MongoDB GridFS support
  3. Spring Data MongoDB Hello World Example
  4. Java MongoDB : Save Image Example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
7 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
6 Comment authors
DavidselvakumarAegidius????jay patel Recent comment authors
newest oldest most voted
David
Guest
David

Hi.
This piece of code:
List result = gridOperations.find(
new Query().addCriteria(Criteria.where(“filename”).is(“testing.png”)));

give me an error:
Type mismatch: cannot convert from GridFSFindIterable to List

Any idea?
Thanks

selvakumar
Guest
selvakumar

I want to persist WAR file into mongoDB. I am trying to persist WAR file size around 11,456KB but to save this WAR file into mongoDB takes around 2.5 min to complete full persistence which is never acceptable by customer.

Can you give better approach for this?

Aegidius
Guest
Aegidius

Where is the definition of “mappingMongoConverter()”;

????
Guest
????

?ow to retrieve two and more image binary files at once?

Roma
Guest
Roma

Very good ! Thanks for your work!))))

trackback
Java MongoDB Tutorial

[…] Spring Data MongoDB : Save binary file, GridFS example Use GridFS in Spring Data MongoDB, to save the binary file in MongoDB. […]

jay patel
Guest
jay patel

Really good post mkyong…have a quick question..As MongoDB suggests to use GridFS for files larger than 16 MB, what if I want to use BSON to store small size files like in 10 KB size? I tried to look for similar example which uses “MongoDB Java Driver + Spring” to achieve this but no luck? Do you have any working example of the same or can help point one?