12. MongoDB : GridFS - to store (static data, audio, video large files)
**************************************************************************
//save file on db
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.save();
//get all grid files
DBCursor cursor = gfsPhoto.getFileList();
//get particular grid file
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
//remove grid file from db
gfsPhoto.remove(gfsPhoto.findOne(newFileName));
**************************************************************************
bez we know 16MB is the max in document.
GridFS -> how it stores more than 16MB, internally it split in to chunks and stores
###############################JAVA PROGRAM TO STORE/READ/DELETE GRIDFILE FROM DB###############################################
-- Download JDK 1.8 (Version that you prefer) for Windows/Linux
-- Install Eclipse oxygen
-- Create a project in eclipse
-- Create a simple Java Class in eclipse
-- Use the code below to upload an image file
-- Get these dependencies and add it to the java classes build path
mongodb-driver-core-3.4.2.jar
mongodb-driver-3.4.2.jar
bson-3.4.2.jar
https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/3.4.2 -> mongodb-driver-core-3.4.2.jar
https://mvnrepository.com/artifact/org.mongodb/mongodb-driver/3.4.2 -> mongodb-driver-3.4.2.jar
https://mvnrepository.com/artifact/org.mongodb/bson/3.4.2 -> bson-3.4.2.jar
##############################################################################
package com.mongodb.gridfs;
import java.io.File;
import java.io.IOException;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
public class UploadFile {
public static void main(String[] args) throws IOException {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("sample");
String newFileName = "gridFS-java-image";
File imageFile = new File("C:\\Users\\Pictures\\MyFile.png");
// create a "photo" namespace
GridFS gfsPhoto = new GridFS(db, "photo");
// get image from local drive
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
// set the new file name for identity
gfsFile.setFilename(newFileName);
// save the image file to mongoDB
gfsFile.save();
// print the result
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()){
System.out.println(cursor.next());
}
// get the image file by it's filename
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
// save it to a new image file
imageForOutput.writeTo("C:\\Users\\Pictures\\MyFileFromMongDB.png");
System.out.println("Done");
// Remove the file.
gfsPhoto.remove(gfsPhoto.findOne(newFileName));
// close the connection
mongoClient.close();
}
}
##############################################################################
No comments:
Post a Comment