版权声明:本文为博主原创文章,未经博主允许不得转载,如果你觉得有用的话,你可以收藏一下,或者评论一下,也可以关注下我,嘿嘿,你要是不听话,我的大刀可不是好玩的哈,想想心里都害怕,哼。快给我点个赞吧 https://blog.csdn.net/weixin_44446298/article/details/88056161
GridFS介绍
- GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成开发。
它的工作原理是:
在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks,
用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。从GridFS中读取文件要对文件的各各块进行组装、合并。
我在写一个spingboot项目,数据库用的是mongoDB,然后发现它里面有个存储文件用的GirdFs,感觉还是挺好用的,但是,网上又没找到详细教程,于是自己写了一个demo,大家有兴趣可以下载:
https://download.csdn.net/download/weixin_44446298/10982983
1.关于存文件
@Autowired
GridFsTemplate gridFsTemplate;
@Test
public void contextLoads() throws FileNotFoundException {
File file = new File("d:/ziliao/index_banner.ftl");
FileInputStream fileInputStream = new FileInputStream(file);
//向Girdfs存储文件
ObjectId objectId = gridFsTemplate.store(fileInputStream, "测试文件0101");
String s = objectId.toString();
System.out.println(s);
}
存储原理说明:
- 文件存储成功得到一个文件id 此文件id是fs.files集合中的主键。
可以通过文件id查询fs.chunks表中的记录,得到文件的内容。
2.读取文件
2.1添加一个config类,代码如下:
//获取配置文件中数据库信息
@Value("${spring.data.mongodb.database}")
String db;
//GridFSBucket用于打开下载流
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient) {
MongoDatabase database = mongoClient.getDatabase(db);
GridFSBucket gridFSBucket = GridFSBuckets.create(database);
return gridFSBucket;
}
2.2测试代码
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
GridFSBucket gridFSBucket;
@Test
public void queryFile() throws IOException {
String id="5c78970cc4e1b125e0999681";
//根据id查询文件
GridFSFile gridFSFile =
gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
//打开流下载对象
GridFSDownloadStream downloadStream =
gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//获取流对象
GridFsResource gridFsResource=new GridFsResource(gridFSFile,downloadStream);
//获取数据
String s = IOUtils.toString(gridFsResource.getInputStream(),"UTF-8");
System.out.println("打印文件:"+s);
}
3,删除文件
//删除文件
@Test
public void testDelFile() throws IOException {
//根据文件id删除fs.files和fs.chunks中的记录
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92")));
}