首页 > 其他 > 详细

GridFS的应用

时间:2019-11-28 20:07:12      阅读:98      评论:0      收藏:0      [点我收藏+]

GridFS介绍

GridFSMongoDBCMS使MongoDB使GridFS

工作原理:

GridFS256KBGridFS使collectionchunks,files

从GridFS中读取文件要对文件的各个块进行组装、合并。

1、存文件

测试代码如下

 1    @Test
 2     public void testGridFs() throws FileNotFoundException {
 3         //要存储的文件
 4         File file = new File("d:/index_banner.html");
 5         //定义输入流
 6         FileInputStream inputStram = new FileInputStream(file);
 7         //向GridFS存储文件
 8         ObjectId objectId = = gridFsTemplate.store(inputStram, "轮播图测试文件01", "");
 9         //得到文件ID
10         String fileId = objectId.toString();
11         //输出文件
12         System.out.println(file);
13     }

 

存储原理说明:

文件存储成功得到一个文件id

此文件id是fs.files集合中的主键。

可以通过文件id查询fs.chunks表中的记录,得到文件的内容。

 

 2、读取文件

1)在config包中定义Mongodb的配置类,如下:

GridFSBucket用于打开下载流对象

 

 1 @Configuration
 2 public class MongoConfig {
 3 ?
 4     @Value("${spring.data.mongodb.database}")
 5     String db;
 6 ?
 7     @Bean
 8     public GridFSBucket getGridFSBucket(MongoClient mongoClient){
 9         MongoDatabase database = mongoClient.getDatabase(db);
10         GridFSBucket bucket = GridFSBuckets.create(database);
11         return bucket;
12     }
13 }
14 ?

 

${spring.data.mongodb.database}:用于指定配置文件中的数据库
1 #在springboot的application.yml的配置文件中配置
2 
3 spring:
4   data:
5     mongodb:
6       uri:  mongodb://localhost:27017
7       database: xc_cms

 

 

2)测试代码如下

 1  @SpringBootTest
 2   @RunWith(SpringRunner.class)
 3   public class GridFsTest {
 4 ?
 5     @Autowired
 6     GridFsTemplate gridFsTemplate;
 7 ?
 8     @Autowired
 9     GridFSBucket gridFSBucket;
10     
11     @Test
12     public void queryFile() throws IOException {
13         //获取id
14         String fileId = "5b9c54e264c614237c271a99";
15         //根据id查询文件(_id数据库中fileId对应的键值)
16         GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
17         //打开下载流对象
18         GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
19         //创建gridFsResource,用于获取流对象
20         GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
21         //获取流中的数据
22         String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");
23         System.out.println(s);
24     }
25     ...

 

 

3、删除文件

1 //删除文件
2 @Test
3 public void testDelFile() throws IOException {
4     //根据文件id删除fs.files和fs.chunks中的记录
5     gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92")));
6 }

 

 

 

GridFS的应用

原文:https://www.cnblogs.com/foshuo-cv/p/11953026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!