1,798
社区成员
发帖
与我相关
我的任务
分享
/**
* 保存文件
* @param collectionName
* @param mongoFile
*/
public boolean saveFiles(String collectionName, MongoFile mongoFile){
try{
// DB db = mongoTemplate.getDb();
// DBCollection mongdb_pic = db.getCollection(collectionName);
// DBObject dbObject = new BasicDBObject();
// if(mongoFile.getFile() != null){
// byte[] bytes = FileUtil.file2byte(mongoFile.getFile());
//
// Binary binary = new Binary(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);
DB db = mongoTemplate.getDb();
GridFS gridFS = new GridFS(db, collectionName);
GridFSInputFile gfs = 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 (Exception e){
logger.error("Mongo数据操作>>存储文件发送错误>>error:" + e.toString());
e.printStackTrace();
return false;
}
return true;
}
/**
* 查询文件
* @param collectionName
* @param filename
* @return
*/
public GridFSDBFile retrieveFileOne(String collectionName, String filename) {
try {
DB db = mongoTemplate.getDb();
GridFS gridFS = new GridFS(db, collectionName);
GridFSDBFile dbfile = gridFS.findOne(filename);
if (dbfile != null) {
return dbfile;
}
} catch (Exception e) {
logger.error("Mongo数据操作>>获取文件发送错误>>error:" + e.toString());
e.printStackTrace();
}
return null;
}