方法1:采用GridFSBucket对象进行下载,请看下方
/**
* 下载导出文件到服务器(新方法)
* @param mac
* @param filenames 文件名称集合
* @param uploadpath 文件所在得绝对路径
* @return
*/
public static boolean downFilesByNames(MongoAttachConnect mac, Set filenames, String uploadpath){
if(uploadpath == null || uploadpath.isEmpty())
{
return false;
}
else if(!uploadpath.endsWith("\\")){
uploadpath += "\\";
}
MongoClient mongoClient = MongoClientBuild.GetMongoAttachClient(mac);
MongoDatabase database = mongoClient.getDatabase(mac.BaseName);
GridFSBucket gridFSBucket = GridFSBuckets.create(database);
String finalDownpath = uploadpath;
//根据文件名下载,指定下载版本,默认下载最新版本
GridFSDownloadOptions downloadOptions = new GridFSDownloadOptions().revision(0);
filenames.forEach(name->{
FileOutputStream streamToDownloadTo = null;
try {
streamToDownloadTo = new FileOutputStream(finalDownpath+name);
//根据文件名 下载文件
gridFSBucket.downloadToStream(name, streamToDownloadTo, downloadOptions);
streamToDownloadTo.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return true;
}
方法2:采用GridFS对象进行下载操作:
/**
* 下载导出文件到服务器(老方法)
* @param mac
* @param filenames
* @param downpath
* @return
*/
public static boolean downFilesByNames(MongoAttachConnect mac, Set filenames, String downpath){
if(downpath == null || downpath.isEmpty())
{
return false;
}
else if(!downpath.endsWith("\\")){
downpath += "\\";
}
MongoClient mongoClient = MongoClientBuild.GetMongoAttachClient(mac);
//高版本驱动会提示方法已过期,不推荐使用
DB db = mongoClient.getDB(mac.BaseName);
GridFS fs = new GridFS(db);
String finalDownpath = downpath;
filenames.forEach(name->{
GridFSDBFile one = fs.findOne(name);
try {
one.writeTo(finalDownpath +name);
} catch (IOException e) {
e.printStackTrace();
}
});
return true;
}