springboot中使用GridFS上传文件、查询文件、删除文件
GridFS介绍
- GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成开发。
它的工作原理是:
在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks,
用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。从GridFS中读取文件要对文件的各各块进行组装、合并。
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表中的记录,得到文件的内容。
//获取配置文件中数据库信息
@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
publicvoid 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")));
}
推荐阅读
- 热闹中的孤独
- Shell-Bash变量与运算符
- JS中的各种宽高度定义及其应用
- 2021-02-17|2021-02-17 小儿按摩膻中穴-舒缓咳嗽
- 深入理解Go之generate
- 由浅入深理解AOP
- 异地恋中,逐渐适应一个人到底意味着什么()
- 【译】20个更有效地使用谷歌搜索的技巧
- Activiti(一)SpringBoot2集成Activiti6
- 我眼中的佛系经纪人