mongodb版本是3.4.7
使用GridFS存取图片
代码如下
/**
*保存文件
*@paramcollectionName
*@parammongoFile
*/
publicbooleansaveFiles(StringcollectionName,MongoFilemongoFile){
try{
//DBdb=mongoTemplate.getDb();
//DBCollectionmongdb_pic=db.getCollection(collectionName);
//DBObjectdbObject=newBasicDBObject();
//if(mongoFile.getFile()!=null){
//byte[]bytes=FileUtil.file2byte(mongoFile.getFile());
//
//Binarybinary=newBinary(bytes);
//dbObject.put("imgByte",binary);
//}
//dbObject.put("id",mongoFile.getId());
//dbObject.put("fileName",mongoFile.getFileName());
//dbObject.put("fileSize",mongoFile.getFileSize());
//dbObject.put("descs",mongoFile.getDescs());
//dbObject.put("fileType",mongoFile.getFileType());
//dbObject.put("contentType",mongoFile.getContentType());
//dbObject.put("oldName",mongoFile.getContentType());
//mongdb_pic.save(dbObject);
DBdb=mongoTemplate.getDb();
GridFSgridFS=newGridFS(db,collectionName);
GridFSInputFilegfs=gridFS.createFile(mongoFile.getFile());
System.out.println("文件大小:"+mongoFile.getFile().length());
gfs.setChunkSize(mongoFile.getFile().length());
gfs.setFilename(mongoFile.getFileName());
gfs.put("_id",mongoFile.getId());
gfs.put("fileName",mongoFile.getFileName());
gfs.put("fileSize",mongoFile.getFileSize());
gfs.put("descs",mongoFile.getDescs());
gfs.put("fileType",mongoFile.getFileType());
gfs.put("contentType",mongoFile.getContentType());
gfs.put("oldName",mongoFile.getOldFileName());
gfs.save();
}catch(Exceptione){
logger.error("Mongo数据操作>>存储文件发送错误>>error:"+e.toString());
e.printStackTrace();
returnfalse;
}
returntrue;
}
/**
*查询文件
*@paramcollectionName
*@paramfilename
*@return
*/
publicGridFSDBFileretrieveFileOne(StringcollectionName,Stringfilename){
try{
DBdb=mongoTemplate.getDb();
GridFSgridFS=newGridFS(db,collectionName);
GridFSDBFiledbfile=gridFS.findOne(filename);
if(dbfile!=null){
returndbfile;
}
}catch(Exceptione){
logger.error("Mongo数据操作>>获取文件发送错误>>error:"+e.toString());
e.printStackTrace();
}
returnnull;
}
分 -->
|