Java MongoDB Driver 3.3.0 - Upload, Download, Delete and Read Image using GridFS API

 Posted On  | Yashwant Chavan 

In this article we will learn how to upload (Save), download, delete, rename and read Image using MongoDB 3.3.0 Java driver GridFS API.

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. The chunks collection stores the file chunks, and the files collection stores the file metadata

Tools and Technologies

Basically we are using below maven dependencies

  1. Maven 3.0.4
  2. JDK 1.8
  3. Mongo Java Driver 3.3.0

Maven Dependencies

To use the mongodb java driver, Define respected maven dependencies of mongo-java-driver in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.technicalkeeda</groupId>
 <artifactId>JavaExamples</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <build>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>org.mongodb</groupId>
   <artifactId>mongo-java-driver</artifactId>
   <version>3.3.0</version>
  </dependency>
 </dependencies>
</project>

Introduction to GridFSBucket and its API

We are using GridFSBucket to deal with different operation of GridFS like upload, download and delete etc. To create a GridFSBucket we will use GridFSBuckets factory class and it uses instance of a MongoDatabase.

 MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
 GridFSBucket gridBucket = GridFSBuckets.create(database);

uploadFromStream() - Uploads the contents of the given InputStream to a GridFS bucket.

downloadToStream() - Downloads the contents of the latest version of the stored file specified by filename and writes the contents to the destination Stream.

find() - Finds all documents in the files collection. Which returns the GridFSFindIterable

delete() - Given a id, delete this stored file's files collection document and associated chunks from a GridFS bucket.

rename() - Renames the stored file with the object id.

GridFSUploadOptions are customizable option used when uploading files into GridFS.

Upload Image into MongoDB database

 public ObjectId upload(String filePath,String fileName) {
  System.out.println("Calling upload...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
  ObjectId fileId = null;
  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);
   InputStream inputStream = new FileInputStream(new File(filePath));
   // Create some custom options
   GridFSUploadOptions uploadOptions = new GridFSUploadOptions().chunkSizeBytes(1024).metadata(new Document("type", "image").append("upload_date", format.parse("2016-09-01T00:00:00Z")).append("content_type", "image/jpg"));
   fileId = gridBucket.uploadFromStream(fileName, inputStream, uploadOptions);

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

Upload Image Output

> show collections
fs.chunks
fs.files
system.indexes
> db.fs.files.find()
{ "_id" : ObjectId("57e2a00efe820219dcb7b17a"), "filename" : "baby-boy", "length" : NumberLong(165709), "chunk
Size" : 1024, "uploadDate" : ISODate("2016-09-21T14:58:22.496Z"), "md5" : "b38332850c02f4193bbfa9fb3bdc9bb3",
"metadata" : { "type" : "image", "upload_date" : ISODate("2016-08-31T18:30:00Z"), "content_type" : "image/jpg"
 } }
 
{ "_id" : ObjectId("57e2a00efe820219dcb7b21e"), "filename" : "baby-girl", "length" : NumberLong(3329696), "chu
nkSize" : 1024, "uploadDate" : ISODate("2016-09-21T14:58:23.518Z"), "md5" : "cab70c802feb480f17cc8051a7f232e3"
, "metadata" : { "type" : "image", "upload_date" : ISODate("2016-08-31T18:30:00Z"), "content_type" : "image/jp
g" } }

>

Download / Save Image from MongoDB database

 
  // Download File
    public void download(String fileName) {
  System.out.println("Calling download...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);

   FileOutputStream fileOutputStream = new FileOutputStream("C:/img/download-baby-image.jpg");
   gridBucket.downloadToStream(fileName, fileOutputStream);
   fileOutputStream.close();

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    } 

Rename File Name

 
  public void rename(ObjectId objectId,String newFileName) {
  System.out.println("Calling rename...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);
   gridBucket.rename(objectId, newFileName);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    } 

Delete File

 
  public void delete(ObjectId objectId) {
  System.out.println("Calling delete...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);
   gridBucket.delete(objectId);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    } 

Find/Get/Retrieve Image from MongoDB

 
  public void find(ObjectId objectId) {
  System.out.println("Calling find...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);

   GridFSFile gridFSFile = gridBucket.find(eq("_id",objectId)).first();
   System.out.println("File Name:- " + gridFSFile.getFilename());
   System.out.println("Meta Data:- " + gridFSFile.getMetadata());

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    } 

Find/Get/Retrieve All images from MongoDB

 
  public void findAll() {
  System.out.println("Calling findAll...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);

   gridBucket.find().forEach(new Block<GridFSFile>() {
   @Override
   public void apply(final GridFSFile gridFSFile) {
    System.out.println("File Name:- " + gridFSFile.getFilename());
    System.out.println("Meta Data:- " + gridFSFile.getMetadata());
   }
   });

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    } 

Complete GridFS Example

Here is the complete example

package com.technicalkeeda.app;

import static com.mongodb.client.model.Filters.eq;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;

public class GridFSExample {
    public static void main(String[] args) {
  Logger mongoLogger = Logger.getLogger( "org.mongodb.driver" );
  mongoLogger.setLevel(Level.SEVERE); 
  
  GridFSExample gridFs = new GridFSExample();
  ObjectId babyBoyObjectId = gridFs.upload("C:/img/baby-boy.jpg","baby-boy");
  ObjectId babyGirlObjectId = gridFs.upload("C:/img/baby-girl.jpg","baby-girl");
  gridFs.findAll();
  gridFs.find(babyGirlObjectId);
  gridFs.download("baby-boy");
  gridFs.rename(babyBoyObjectId,"new-baby-image");
  gridFs.delete(babyBoyObjectId);
  gridFs.findAll();
    }

    // Upload File
    public ObjectId upload(String filePath,String fileName) {
  System.out.println("Calling upload...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
  ObjectId fileId = null;
  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);
   InputStream inputStream = new FileInputStream(new File(filePath));
   // Create some custom options
   GridFSUploadOptions uploadOptions = new GridFSUploadOptions().chunkSizeBytes(1024).metadata(new Document("type", "image").append("upload_date", format.parse("2016-09-01T00:00:00Z")).append("content_type", "image/jpg"));
   fileId = gridBucket.uploadFromStream(fileName, inputStream, uploadOptions);

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }

  return fileId;
    }

    
    // Find All
    public void findAll() {
  System.out.println("Calling findAll...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);

   gridBucket.find().forEach(new Block<GridFSFile>() {
   @Override
   public void apply(final GridFSFile gridFSFile) {
    System.out.println("File Name:- " + gridFSFile.getFilename());
    System.out.println("Meta Data:- " + gridFSFile.getMetadata());
   }
   });

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    }
    
    // Find by Id
    public void find(ObjectId objectId) {
  System.out.println("Calling find...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);

   GridFSFile gridFSFile = gridBucket.find(eq("_id",objectId)).first();
   System.out.println("File Name:- " + gridFSFile.getFilename());
   System.out.println("Meta Data:- " + gridFSFile.getMetadata());

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    }
    
    // Download File
    public void download(String fileName) {
  System.out.println("Calling download...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);

   FileOutputStream fileOutputStream = new FileOutputStream("C:/img/download-baby-image.jpg");
   gridBucket.downloadToStream(fileName, fileOutputStream);
   fileOutputStream.close();

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    }
    
    //Rename File 
    public void rename(ObjectId objectId,String newFileName) {
  System.out.println("Calling rename...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);
   gridBucket.rename(objectId, newFileName);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    }

    //Delete File
    public void delete(ObjectId objectId) {
  System.out.println("Calling delete...");
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  try {
   MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
   GridFSBucket gridBucket = GridFSBuckets.create(database);
   gridBucket.delete(objectId);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   mongoClient.close();
  }
    }
}

GridFS Example Ouput

Calling upload...
Calling upload...
Calling findAll...
File Name:- baby-boy
Meta Data:- Document{{type=image, upload_date=Thu Sep 01 00:00:00 IST 2016, content_type=image/jpg}}
File Name:- baby-girl
Meta Data:- Document{{type=image, upload_date=Thu Sep 01 00:00:00 IST 2016, content_type=image/jpg}}
Calling find...
File Name:- baby-girl
Meta Data:- Document{{type=image, upload_date=Thu Sep 01 00:00:00 IST 2016, content_type=image/jpg}}
Calling download...
Calling rename...
Calling delete...
Calling findAll...
File Name:- baby-girl
Meta Data:- Document{{type=image, upload_date=Thu Sep 01 00:00:00 IST 2016, content_type=image/jpg}}


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0408 seconds.