Java MongoDB Save Pictures

This article describes how to save a picture file to MongoDB using the GridFS API.The GridFS API can also save other binary files, such as video and music files.

1. Save pictures

The following code uses the photo namespace, and the new filename saves the picture to MongoDB.

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

2. Get pictures

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

Output, pictures are saved in JSON format as follows:

{
    "_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 pictures

Use DBCursor to iterate through all pictures.

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

4. Save as another picture

Get a picture from MongoDB and save it as another picture.

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

5. Delete pictures

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

Full Instance

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

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

public class SaveImage {
    public static void main(String[] args) {

        try {

            MongoClient mongoClient = new MongoClient("localhost", 27017);
            DB db = mongoClient.getDB("imagedb");
            DBCollection collection = db.getCollection("dummyColl");

            String newFileName = "mkyong-java-image";

            File imageFile = new File("mongodb.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("mongodbNew.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();
        }

    }
}

Tags: MongoDB Java JSON

Posted on Mon, 29 Jun 2020 12:24:51 -0400 by NewPHP_Coder