Java mongodb driver provides the api to store large files in to Mongo db through java. Below are the important class which helps to do the large files operation in mongodb
GridFS
GridFS is a specification for storing large files in MongoDB
GridFSDBFile
This class enables to retrieve a GridFS file metadata and content.
GridFSInputFile
This class enables to get image file from local drive.
Example
import java.io.File;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
public class SaveImage {
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 = "myfile";
File imageFile = new File("java.jpg");
// 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("java1.jpg");
// remove the image file from mongoDB
gfsPhoto.remove(gfsPhoto.findOne(newFileName));
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
{ "filename" : "category" , "aliases" : null , "chunkSize" : 261120 , "uploadDate" : { "$date" : "2015-09-26T03:19:50.975Z"} , "length" : 11121 , "_id" : { "$oid" : "56060ed6c33a6f1275703944"} , "contentType" : null , "md5" : "e8bf9f694881c75d766355d3f9d770c2"}
{ "filename" : "myfile" , "aliases" : null , "chunkSize" : 261120 , "uploadDate" : { "$date" : "2016-01-24T07:38:00.099Z"} , "length" : 48420 , "_id" : { "$oid" : "56a47f587661b934c94049ed"} , "contentType" : null , "md5" : "8691076763f2b8b112c1a4e05b0cd775"}
Done
Download source code from
https://github.com/kkvinodkumaran/myrepository/tree/master/mymongoexamples
No comments:
Post a Comment