java小白又來了,哈哈
這次記錄操作mongodb的GridFS庫
在插入文件後,同時給該Document添加其它字段,比如過期時間字段,
直接上代碼示例:
/**
* 上載文件到MongoGridFS服務器
* @param mac
* @param filenames 文件路徑集合(d:\77\77\hello.doc)
* @param expireat 文件過期時間
* @return
*/
public static boolean uploadFilesByNames(MongoAttachConnect mac, Set<String> filenames,Date expireat){
//獲得MongoClient對象
MongoClient mongoClient = MongoClientBuild.GetMongoAttachClient(mac);
//獲得MongoDatabase對象
MongoDatabase db = mongoClient.getDatabase(mac.BaseName);
AtomicBoolean isOK = new AtomicBoolean(true);
GridFSBucket gridFS = GridFSBuckets.create(db);
// Create some custom options
GridFSUploadOptions options = new GridFSUploadOptions();
filenames.forEach(filename->{
File f =new File(filename);
if(!f.exists()){
isOK.set(false);
return;
}
try {
//獲取文件名
String flame = f.getName();
//獲取文件名類型 .pdf
String fileTye=flame.substring(flame.lastIndexOf("."),flame.length());
//定義輸入流
FileInputStream fileInputStream=new FileInputStream(f);
//設置除filename以爲的其他信息(此處生成的是子文檔字段)
//不需要可以不用設置
Document metadata = new Document();
metadata.append("contentType", fileTye);
options.metadata(metadata);
//上傳
gridFS.uploadFromStream(flame, fileInputStream,options);
/*更新添加過期字段 - 非子文檔字段*/
//注意update文檔裏要包含"$set"字段
Document update = new Document();
update.append("$set", new Document("expireAt", expireat));
//查找到剛剛新增得附件,然後進行更新過期字段
db.getCollection("fs.files").updateOne(Filters.eq("filename",flame),update);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
});
return isOK.get();
}