日期:2014-05-16 浏览次数:20438 次
public class Mongofs { private static final String USER = "rechard"; private static final String PASS = "root"; public static void main(String[] args) throws Exception { Mongo m = new Mongo("localhost"); DB db = m.getDB("newdb"); boolean auth = db.authenticate(USER, PASS.toCharArray()); if (auth) { DBCollection coll = db.getCollection("testColl"); db.requestStart(); String file, newFilename, bucket, saveTo; bucket = "fs"; newFilename = "mm"; file = "/home/rechard/Pictures/105066115253.jpg"; saveTo = "/home/rechard/Desktop/1.jpg"; storeFile(db, bucket, file, newFilename); findSingleFileAndSaveAs(db, bucket, newFilename, saveTo); remove(db, bucket, newFilename); db.requestDone(); } } /** * 存储文件到mongo * @param db * @param bucket * @param file * @param fn * @throws Exception */ static void storeFile(DB db, String bucket, String file, String fn) throws Exception { File files = new File(file); // 创建一个GridFS实例 GridFS gfs = new GridFS(db, bucket); GridFSInputFile gfsInput = gfs.createFile(files); // 指定一个GridFS实体的名字 gfsInput.setFilename(fn); gfsInput.save(); } /** * 查找单个文件并保存 * @param db * @param bucket * @param fn * @param saveTo * @throws Exception */ static void findSingleFileAndSaveAs(DB db, String bucket, String fn, String saveTo) throws Exception { GridFS gfs = new GridFS(db, bucket); GridFSDBFile dbFile = gfs.findOne(fn); //System.out.println(dbFile); if (dbFile != null) System.out.println("file size:" + dbFile.writeTo(saveTo)); } /** * 从mongodb删除文件 * @param db * @param bucket * @param fn */ static void remove(DB db, String bucket, String fn) { GridFS gfs = new GridFS(db, bucket); gfs.remove(fn); } }
{ "_id" : <unspecified>, // 文件的唯一标示id,由mongo自动创建 "length" : data_number, // 文件的大小 "chunkSize" : data_number, // 块大小,默认是256k "uploadDate" : data_date, // 存储时间 "md5" : data_string // 文件的md5码 }