Main Tutorials

Java MongoDB : Save image example

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.

Note
For detail explanation, read this MongoDB GridFS manual.

1. Save image

Code snippets to save an image file into MongoDB, under “photo” namespace, and assign a new “filename” for the saved image.


	String newFileName = "mkyong-java-image";
	File imageFile = new File("c:\\JavaWebHosting.png");
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
	gfsFile.setFilename(newFileName);
	gfsFile.save();

2. Get image

Code snippets to get the saved image by its “filename”.


	String newFileName = "mkyong-java-image";
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
	System.out.println(imageForOutput);

Output, the image is saved as following JSON format.


{ 
	"_id" : 
	{ 
		"$oid" : "4dc9511a14a7d017fee35746"
	} , 
	"chunkSize" : 262144 , 
	"length" : 22672 , 
	"md5" : "1462a6cfa27669af1d8d21c2d7dd1f8b" , 
	"filename" : "mkyong-java-image" , 
	"contentType" :  null  , 
	"uploadDate" : 
	{ 
		"$date" : "2011-05-10T14:52:10Z"
	} , 
	"aliases" :  null 
}

3. Print all saved images

Code snippets to get all the saved files from MongoDB and iterate it with DBCursor.


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

4. Save into another image

Code snippets to get an image file from MongoDB and output it to another image file.


	String newFileName = "mkyong-java-image";
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
	imageForOutput.writeTo("c:\\JavaWebHostingNew.png"); //output to new file

5. Delete image

Code snippets to delete an image file.


	String newFileName = "mkyong-java-image";
	GridFS gfsPhoto = new GridFS(db, "photo");
	gfsPhoto.remove(gfsPhoto.findOne(newFileName));

Full Example

Full example to work with image, via Java MongoDB GridFS API. See comments for explanation.


package com.mkyong.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;

/**
 * Java MongoDB : Save image example
 * 
 */

public class SaveImageApp {
	public static void 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 = new File("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“.

Reference

  1. MongoDB GridFS Specification

About Author

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

Comments

Subscribe
Notify of
18 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Rabin
3 years ago

I tried doing this using mongodb stitch but it doesn’t work. It cannot import the gridfs classes and if i introduce mongo-java-driver it clashes with mongodb-stitch SDK. Is there a way to solve this?

tanc13
6 years ago

mongo.getDB() is departed and don’t cast to MongoDatabase!How use MongoDatabase with GridFS&?

Mihai Gheoace
2 years ago

This is rather old. Still, if you want to use it, for maven you can add this dependency for mongo driver:

<dependency>

      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver</artifactId>
      <version>3.6.3</version>
    </dependency>

And select a good java version, I suggest Java 11 or 17 works fine.

Jamie
4 years ago

will this code work on android studio?

Pradeep Kumar Reddy
7 years ago

how to store a file to mongodb from mongo shell

dffff
9 years ago

dfdfd

Gaurav Ashara
9 years ago

Great article , but i have some question.I have web application in which i have facility any if user can download gridfs file. If i store my gridfs file using WrtieTo method in server side folder and user can download it.I think it is not right way. Plz suggest me some approach for this .

Thank you very much

Dharshan
10 years ago

Great article to get started on GridFS. Here are some reasons you want to use GridFS on MongoDB – http://blog.mongodirector.com/when-to-use-gridfs/

Majid Lotfi
10 years ago

Thanks lot, this is a nice tutorial, can you please show me how to use this technic as a web application, so the user can see a
Pinterest
page showing the latest (last images saved) first ?

thanks lot.

Manohar
10 years ago

Please reply soon… Its urgent!!!
I am getting a run time error like this—-
Exception in thread “main” java.lang.NoClassDefFoundError: com/mongodb/MongoExce
ption
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.mongodb.MongoException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 6 more
Please HELP
Thanks in advance!!!

sdsdf
8 years ago
Reply to  Manohar

never replay u

ajit
10 years ago

This is too good. I am loving this tutorial. No one has posted so simple tutorial of mongoDB.Thanks mkyong my saviour.

Jitendra
10 years ago

It is very nice tutorial.
I want to execute query:
some of two fields should less than or equal to current date.
How we can do that?
I put below query but it didn’t work. Can you please suggest?
List savedUser2 = mongoOperation.find(
new Query(Criteria.where(“(cachettl + create_time)”).lte(System.currentTimeMillis())), com.mkyong.user.EventListner.class,
“events”);

Kev Ng
11 years ago

That’s wonderful and very simple.
Thank you !

Majid Azimi
11 years ago

Awesome tutorial. Simple and effective…

cmdr
12 years ago

Hi

How can we perform the same operations using the spring data api.

Regards

Banu
7 years ago

How to add additional meta data in fs.files using GridFS ?

Ose Abunaw
8 years ago

I love this guy. He has helped me in so many ways and does not
even know it.