There are many times that you need to save images for your entities, a profile image, or photos of your products that are stored in the database. There are also many ways to save the images. You can save them in the database as BLOB fields (not a good idea) or come up with a folder structure to be able to find them fast and efficient.

MongoDB, a NoSql database, has a mechanism to store images or files which uses a specific File System calld GridFS.

In order to save a file in MongoDB GridFS, we need to create an instance of GridFS object associated to a specific database and type. In the following example we get the database instance using mongoTemplate.getDb() method and we know the type name is photo (this is chosen by you. For example you can call it myphotos or customerPhotos, etc). Then we create the file (GridFSInputFile) and set required (desired) properties and save it.

public String saveImage(byte[] content,String fileName,String contentType) {

// create a table/collection or use the existing one
GridFS gfsPhoto = new GridFS(mongoTemplate.getDb(), "photo");

GridFSInputFile gfsFile = gfsPhoto.createFile(content);

gfsFile.setFilename(fileName);
gfsFile.setContentType(contentType);
gfsFile.save();

return gfsFile.getId().toString();
}

 

Reading the image from the database is as easy as saving it. Obviously we require the identity of the image. In this case we assume that we have the ID.

GridFS gfsPhoto = new GridFS(mongoTemplate.getDb(), "photo");

GridFSDBFile image = gfsPhoto.findOne(new ObjectId(id));

InputStream stream = image.getInputStream();

Peace of cake. Now, we can use the stream to get the content of the file.

Please note that mongoTemplate is of type org.springframework.data.mongodb.core.MongoTemplate . If you are not using spring framework you can access mongo database in your own way and use it to instantiate GridFS object.