How to Save an Image in MongoDB using Java

Introduction

MongoDB is widely used to store and manage text data, but its capabilities extend far beyond just text. If you’ve been wondering how to save an image in MongoDB, look no further– it’s actually quite easy to store images and other binary data to MongoDB. In this tutorial, we’ll explain how to use the GridFS API to store images in MongoDB.

Prerequisites

It’s important to point out some key prerequisites before we turn our attention to the Java code needed to store images. For this task, there are a few system requirements to keep in mind:

  • You’ll need to confirm that both MongoDB and the MongoDB Java driver are installed and properly configured beforehand.

  • You’ll also need to confirm that the latest Java JDK is properly installed and configured beforehand.

  • Last but not least, you’ll need to ensure that the MongoDB service is running.

NOTE: In this article, we assume that the MongoDB version being used is 4.0 and MongoDB Java Driver is 3.8.2.

The GridFS API

We’ll be using the GridFS API to store images in MongoDB. GridFS is used to store and retrieve files that exceed 16MB, which is the maximum allowed size for a BSON document. GridFS works by breaking up a large file into “chunks” instead of storing it in a single document. The default chunk size for GridFS is 255kB– this means that GridFS will break up a file so that every chunk will have a size of 255kB, except for the final chunk. The final chunk is only as large as needed, depending on how many kilobytes are left at that point.

GridFS makes use of two different collections to store files: One collection is used to store the actual file chunks, while the other is used to hold metadata about the files. If you query GridFS, the driver constructs the file by reassembling the chunks.

Save image

In the following code examples, we’ll save an image file into MongoDB, and we’ll assign a new filename for the saved image.

Instantiate a MongoDB object in Java that will be used to create indexes

The first step in the process is to instantiate a MongoDB object. We’ll use the MongoClient class and create a new instance of the client driver:

// connect to the MongoDB server
MongoClient mongoDbClient = MongoClient('mongodb://localhost:27017');

In the code shown below, we supply the path of the image and its corresponding name:

public ObjectId upload(String filePath,String fileName) {
ObjectId fileId = null;
try {
MongoDatabase imgDb = mongo.getDatabase("imageDatabase");

// Create a gridFSBucket
GridFSBucket gridBucket = GridFSBuckets.create(imgDb);


InputStream inStream = new FileInputStream(new File(filePath));

// Create some customize options for the details that describes
// the uploaded image
GridFSUploadOptions uploadOptions = new GridFSUploadOptions().chunkSizeBytes(1024).metadata(new Document("type", "image").append("content_type", "image/png"));

fileId = gridBucket.uploadFromStream(fileName, inStream, uploadOptions);

} catch (Exception e) {
e.printStackTrace();
} finally {
mongo.close();
}
return fileId;
}

To call the above function in a MongoDB application, use the command shown below:

ObjectId some_name = gridFs.upload("/home/someUser/Documents/Selection_002.png","selection-02");

We pass two important pieces of information into the upload() method. The first is the path of the image file (/home/someUser/system location), and the second is the desired file name to associated with the image file. (selection-02).

To confirm that we successfully stored the image, we can perform a query in the Mongo shell. The results should look like the following:

{
"_id" : ObjectId("5cf246203fd48a35edf2079b"),
"filename" : "selection-02",
"length" : NumberLong(124992),
"chunkSize" : 1024,
"uploadDate" : ISODate("2019-06-01T09:32:16.807Z"),
"md5" : "1af4f9efc8f1d3eafe38e0bbf498ef84",
"metadata" : {
"type" : "image",
"content_type" : "image/png"
}
}

Conclusion

If you’ve only been using MongoDB to manage your text data, you may not be using the system to its fullest extent. MongoDB can also be used for file storage– you can store images and other types of binary files. In this tutorial, we discussed how to save an image in MongoDB. With these instructions, you’ll have no trouble storing images using GridFS.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.