MongoDB supports storing binary files inside it's filesystem GridFS. Spring Data MongoDB provides a GridFsOperations interface as well as the according implementation GridFsTemplate to easily interact with the filesystem. You can setup a GridFsTemplate instance by handing it a MongoDbFactory as well as aMongoConverter:
Example 5.16. JavaConfig setup for a GridFsTemplate
class GridFsConfiguration extends AbstractMongoConfiguration {
// … further configuration omitted@Beanpublic GridFsTemplate gridFsTemplate() {
returnnew GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
}
}
An according XML configuration looks like this:
Example 5.17. XML configuration for a GridFsTemplate
The store(…) operations take an InputStream, a filename and optionally metadata information about the file to store. The metadata can be an arbitrary object which will be marshalled by the MongoConverter configured with the GridFsTemplate. Alternatively you can also provide a DBObject as well.
Reading files from the filesystem can either be achieved through the find(…) or getResources(…) methods. Let's have a look at the find(…) methods first. You can either find a single file matching a Query or multiple ones. To easily define file queries we provide the GridFsCriteria helper class. It provides static factory methods to encapsulate default metadata fields (e.g. whereFilename(), whereContentType()) or the custom one through whereMetaData().
Example 5.19. Using GridFsTemplate to query for files
class GridFsClient {
@Autowired
GridFsOperations operations;
@Testpublicvoid findFilesInGridFs {
List<GridFSDBFile> result = operations.find(query(whereFilename().is("filename.txt")))
}
}
Note
Currently MongoDB does not support defining sort criterias when retrieving files from GridFS. Thus any sort criterias defined on the Query instance handed into the find(…) method will be disregarded.
The other option to read files from the GridFs is using the methods introduced by the ResourcePatternResolver interface. They allow handing an Ant path into the method ar thus retrieve files matching the given pattern.
GridFsOperations extending ResourcePatternResolver allows the GridFsTemplate e.g. to be plugged into an ApplicationContext to read Spring Config files from a MongoDB.
In MongoDB, you can use GridFS to store binary files. In this tutorial, we show you how to use Spring Data’sGridFsTemplate 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
packagecom.mkyong.config;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.mongodb.config.AbstractMongoConfiguration;importorg.springframework.data.mongodb.gridfs.GridFsTemplate;importcom.mongodb.Mongo;importcom.mongodb.MongoClient;/**
* Spring MongoDB configuration file
*
*/
@Configuration
publicclass SpringMongoConfig extends AbstractMongoConfiguration{
@Bean
public GridFsTemplate gridFsTemplate()throwsException{returnnew GridFsTemplate(mongoDbFactory(), mappingMongoConverter());}
@Override
protectedString getDatabaseName(){return"yourdb";}
@Override
@Bean
public Mongo mongo()throwsException{returnnew MongoClient("127.0.0.1");}}
In this tutorial, we show you how to save an image file into MongoDB, via GridFS API. The GridFS APIs are able to serve other binary files as well, like video and music files.
Full example to work with image, via Java MongoDB GridFS API. See comments for explanation.
packagecom.mkyong.core;importjava.io.File;importjava.io.IOException;importjava.net.UnknownHostException;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.DBCursor;importcom.mongodb.Mongo;importcom.mongodb.MongoException;importcom.mongodb.gridfs.GridFS;importcom.mongodb.gridfs.GridFSDBFile;importcom.mongodb.gridfs.GridFSInputFile;/**
* Java MongoDB : Save image example
*
*/publicclass SaveImageApp {publicstaticvoid main(String[] args){try{
Mongo mongo =new Mongo("localhost", 27017);
DB db = mongo.getDB("imagedb");
DBCollection collection = db.getCollection("dummyColl");String newFileName ="mkyong-java-image";File imageFile =newFile("c:\\JavaWebHosting.png");// create a "photo" namespace
GridFS gfsPhoto =new GridFS(db, "photo");// get image file from local drive
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);// set a new filename for identify purpose
gfsFile.setFilename(newFileName);// save the image file into mongoDB
gfsFile.save();// print the result
DBCursor cursor = gfsPhoto.getFileList();while(cursor.hasNext()){System.out.println(cursor.next());}// get image file by it's filename
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);// save it into a new image file
imageForOutput.writeTo("c:\\JavaWebHostingNew.png");// remove the image file from mongoDB
gfsPhoto.remove(gfsPhoto.findOne(newFileName));System.out.println("Done");}catch(UnknownHostException e){
e.printStackTrace();}catch(MongoException e){
e.printStackTrace();}catch(IOException e){
e.printStackTrace();}}}
At the end of the program, a new image file is created in “c:\\JavaWebHostingNew.png“.