Use mongodb to store and read files (pictures, audio, video)
Implementation code example:
package mongo.util; import java.io.File; import java.io.IOException; import java.util.List; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; /** * Use mongodb to store and read files (pictures, audio, video) * @author wangzp */ public class Mon_GridFS { public static void main(String[] args) throws Exception { //saveFile(); readFile(); } /** * Store files * @throws IOException */ public static void saveFile() throws IOException{ //connect to the server, create an instance Mongo mongo = new Mongo("127.0.0.1",27017); //Connect to the database DB db = mongo.getDB("testGridFS"); //The file is implemented on the basis of DB and has nothing to do with tables and documents GridFS gridFS = new GridFS(db); String fileName = "2-2 Database Design.mp4"; File readFile = new File("d:/0202/"+fileName); GridFSInputFile mongofile = gridFS.createFile(readFile); //add the object again mongofile.put("path", "d:/0202/"+fileName); //keep mongofile.save(); } /** * read file, write to disk * @throws Exception */ public static void readFile() throws Exception{ //1. Connect to the server and create an instance Mongo mongo = new Mongo("127.0.0.1",27017); //Connect to the database DB db = mongo.getDB("testGridFS"); //The file is implemented on the basis of DB and has nothing to do with tables and documents GridFS gridFS = new GridFS(db); //2. Find conditions DBObject query = new BasicDBObject(); List<GridFSDBFile> listFile = gridFS.find(query); GridFSDBFile gridFSDBFile = listFile.get(0); //3. Get the file name //Note: not the column name of the table in fs, but according to the properties in the debug gridDBFile String fileName = (String)gridFSDBFile.get("filename"); System.out.println("The file name obtained from MongoDB: "+fileName); //4. Create empty file File writeFile = new File("d:/"+fileName); if(!writeFile.exists()){ writeFile.createNewFile(); } //5. Write to the file gridFSDBFile.writeTo(writeFile); } }
Image location:
mongoDB database client