Mongodb与spring集成(4)------读写mongo GridFs中的文件

来源:互联网 发布:c语言实验报告答案 编辑:程序博客网 时间:2024/06/07 17:58

mongodb里面自带有一个分布式文件系统gridFs,它是以块的方式来存储文件的,一般的存储都够用了,国内一个使用例子是视觉中国使用它来进行上亿数据级的图片存储,可以看出这套文件系统还是挺强大的。下面介绍下如何用spring-data-mongodb来对其进行操作,其实spring-data-mongodb并没有对gridfs进行再次封装,我们只能自己根据需要简单封装下接口,mongodb java api中操作gridfs也是很简单的,1.得到DB对象,2.new 一个GridFSInputFile对象,这个对象相当于一个文件记录,包含文件和与这个文件相关的信息。3.调用save方法保存。读取文件时可以根据文件名和id来对文件进行查询,查询出来一个GridFSDBFile 对象,再把这个对象输出到流或文件中。

先注入MongoDbFactory

@Autowired    private MongoDbFactory mongoDbFactory; 

获得DB对象

DB db = mongoDbFactory.getDb(); 

保存文件(其中FS_NAME相当于gridfs文件系统的表名,可以有多个)

public boolean saveFile(File file, String fileName, String contentType,        DBObject metaData) {             GridFSInputFile gfsInput;      try {           gfsInput = new GridFS(db, FS_NAME).createFile(file);        gfsInput.setFilename(fileName);        gfsInput.setContentType(contentType);        gfsInput.setMetaData(metaData);        gfsInput.save();      } catch (IOException e) {        log.error(e, e);        return false;      }      return true;    } 

通过文件名读取文件

public GridFSDBFile findFileByName(String fileName){      GridFSDBFile gfsFile ;      try {              gfsFile = new GridFS(db, FS_NAME).findOne(fileName);      } catch (Exception e) {        log.error(e, e);        return null;      }      return gfsFile;    } 

通过id读取文件

public GridFSDBFile findFileById(String id){      GridFSDBFile gfsFile ;      try {              gfsFile = new GridFS(db, FS_NAME).find(new ObjectId(id));      } catch (Exception e) {        log.error(e, e);        return null;      }      return gfsFile;    } 
输出文件到OutputStream

    private boolean writeToOutputStream(OutputStream out, GridFSDBFile gfsFile) {          try {                 gfsFile.writeTo(out);          } catch (IOException e) {            log.error(e, e);            return false;          }          return true;        }  



0 0
原创粉丝点击