Home > Java, JSON, mongodb, NOSQL > Storing images in your documentDB – MongoDB

Storing images in your documentDB – MongoDB

MongoDB has special API called GridFS to manipulate the files. It stores the files as bit chunks with 256k. Then we can retrieve the bit sequence to a image again. Keep remember to create a separate namespace to store these image files. I have used a namespace called photo – GridFS gfsPhoto = new GridFS(db,”photo”);
Here is the Java code on how to store an image and retrieve it.
package com.technodyne.core;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class SaveImage {

	public static void main(String[]args){

		try {

			Mongo mongo = new Mongo("",27017);
			DB db = mongo.getDB("imagedb");
			DBCollection collection = db.getCollection("dummyImageCollection");

			String newFileName = "technodyne-java-image";
			File imageFile = new File("C:UsersSUPUNDesktopimages.jpg");

			GridFS gfsPhoto = new GridFS(db,"photo");
			try {
				GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);

				DBCursor cursor = gfsPhoto.getFileList();

				GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);

			} catch (IOException e) {
				// TODO Auto-generated catch block

		} catch (UnknownHostException e) {
			// TODO: handle exception
		catch(MongoException e){
Categories: Java, JSON, mongodb, NOSQL
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: