HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / MongoDB / Java MongoDB: Get/Save Image using GridFS APIs

Java MongoDB: Get/Save Image using GridFS APIs

In previous tutorials, We have learned about MongoDB basics and installing MongoDB in Windows, as well as we learned about Inserting documents in MongoDB and selecting documents from MongoDB. In this tutorial, I am giving few examples of code which will help you when you have to work with images or other binary data types to store/retrieve/delete such data from MongoDB.

For CRUD operations, we will be using MongoDB’s GridFS APIs. In ideal situation, GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16MB. Instead of storing a file in a single document, GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document. By default GridFS limits chunk size to 255k. GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata.

When you query a GridFS store for a file, the driver or client will reassemble the chunks as needed. You can perform range queries on files stored through GridFS. You also can access information from arbitrary sections of files, which allows you to “skip” into the middle of a video or audio file.

GridFS is useful not only for storing files that exceed 16MB but also for storing any files for which you want access without having to load the entire file into memory.

Code Examples List

Save an image into MongoDB
Get/Retrieve an image from MongoDB
Get/Retrieve all images from MongoDB
Save the retrieved image into local file-system
Delete an image from MongoDB

For testing purpose, I have stored an image in temp location (c: drive) named DemoImage.png. I will store this image into MongoDB.

Save an image into MongoDB

private static void saveImageIntoMongoDB(DB db) throws IOException {
	String dbFileName = "DemoImage";
	File imageFile = new File("c:\\DemoImage.png");
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
	gfsFile.setFilename(dbFileName);
	gfsFile.save();
}

Get/Retrieve an image from MongoDB

private static void getSingleImageExample(DB db) {
	String newFileName = "c:/DemoImage";
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
	System.out.println(imageForOutput);
}

Output:

{ "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , 
"md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" :  null  , 
"uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" :  null }

Get/Retrieve all images from MongoDB

private static void listAllImages(DB db) {
	GridFS gfsPhoto = new GridFS(db, "photo");
	DBCursor cursor = gfsPhoto.getFileList();
	while (cursor.hasNext()) {
		System.out.println(cursor.next());
	}
}

Output:

{ "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , 
"md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" :  null  , 
"uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" :  null }

Save the retrived image into local filesystem

private static void saveToFileSystem(DB db) throws IOException {
	String dbFileName = "DemoImage";
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSDBFile imageForOutput = gfsPhoto.findOne(dbFileName);
	imageForOutput.writeTo("c:/DemoImageNew.png");
}

Delete an image from MongoDB

private static void deleteImageFromMongoDB(DB db) {
	String dbFileName = "DemoImage";
	GridFS gfsPhoto = new GridFS(db, "photo");
	gfsPhoto.remove(gfsPhoto.findOne(dbFileName));
}

Complete Example Code

Below is the complete for building above short examples. Feel free to play with it.

package examples.mongodb.crud;

import java.io.File;
import java.io.IOException;

import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class MongoDBBinaryExample 
{
	public static void main(String[] args) throws IOException 
	{
		MongoClient mongo = new MongoClient("localhost", 27017);
		DB db = mongo.getDB("howtodoinjava");
		//Save a image in DB
		saveImageIntoMongoDB(db);
		//Get a image from DB
		getSingleImageExample(db);
		//Get all images from DB
		listAllImages(db);
		saveToFileSystem(db);		
		//Delete images from DB
		deleteImageFromMongoDB(db);
		
		//Verifying if image was deleted or not
		getSingleImageExample(db);
	}
	
	private static void saveImageIntoMongoDB(DB db) throws IOException {
		String dbFileName = "DemoImage";
		File imageFile = new File("c:\\DemoImage.png");
		GridFS gfsPhoto = new GridFS(db, "photo");
		GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
		gfsFile.setFilename(dbFileName);
		gfsFile.save();
	}
	
	private static void getSingleImageExample(DB db) {
		String newFileName = "c:/DemoImage";
		GridFS gfsPhoto = new GridFS(db, "photo");
		GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
		System.out.println(imageForOutput);
	}

	
	private static void listAllImages(DB db) {
		GridFS gfsPhoto = new GridFS(db, "photo");
		DBCursor cursor = gfsPhoto.getFileList();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	}
	
	private static void saveToFileSystem(DB db) throws IOException {
		String dbFileName = "DemoImage";
		GridFS gfsPhoto = new GridFS(db, "photo");
		GridFSDBFile imageForOutput = gfsPhoto.findOne(dbFileName);
		imageForOutput.writeTo("c:/DemoImageNew.png");
	}
	
	private static void deleteImageFromMongoDB(DB db) {
		String dbFileName = "DemoImage";
		GridFS gfsPhoto = new GridFS(db, "photo");
		gfsPhoto.remove(gfsPhoto.findOne(dbFileName));
	}
}


Output:

{ "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" :  null  , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" :  null }
{ "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" :  null  , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" :  null }

null

That’s all for this simple tutorial. Hope it will help someone in need.

Happy Learning !!

Reference: http://docs.mongodb.org/manual/core/gridfs/

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. GANESH

    June 3, 2019

    PLS EXPLAIN HOW TO SHOW THAT IMAGE IN JSP PAGE .IT WILL BW HELPFUL IF U SENT AN EMAIL OR POST HERE AND SEND THE LINK. THANKS IN ADVANCE.

  2. sambhaw

    March 18, 2016

    Do you have similar code for videos mongo db in java

  3. Ali Akhtar

    February 11, 2015

    Plz also provide code for update file in GridFS using Java.

    Thankx in advance

    • Lokesh Gupta

      February 11, 2015

      Hi Ali, nobody update existing binary data. You delete old data and then add new data.
      Sorry i misunderstood your question.

Comments are closed on this article!

Search Tutorials

MongoDB Tutorial

  • MongoDB – Introduction
  • MongoDB – Installation
  • MongoDB – Get/Save Image GridFS
  • MongoDB – Insert Document
  • MongoDB – Query Document

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)