GridFS的增、删、查询

GridFS

GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成 开发。 它的工作原理是: 在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合 (collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数 据信息(文件名称、块大小、上传时间等信息)。 从GridFS中读取文件要对文件的各各块进行组装、合并。

GridFS存文件测试

@Autowired
    GridFsTemplate gridFsTemplate;

    @Test
    public void testGridFsTemplate() throws FileNotFoundException {
        FileInputStream inputStream = new FileInputStream(new File("E:/index_banner.ftl")) ;
        ObjectId objectId = gridFsTemplate.store(inputStream, "index_banner.ftl");
        System.out.println(objectId);
    }

结果:
fs.files保存成功!
存入fs.files成功
fs.chunks保存成功
存入fs.chunks成功

读取文件

在config包中定义Mongodb的配置类,如下: GridFSBucket用于打开下载流对象

@Configuration
public class MongoConfig {
    @Value("${spring.data.mongodb.database}")
    String db ;

    @Bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient){
        MongoDatabase database = mongoClient.getDatabase(db);
        GridFSBucket gridFSBucket = GridFSBuckets.create(database);
        return gridFSBucket ;
    }
}

测试代码如下

@Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    @Test
    public void QueryFile() throws Exception {
        //根据id查询文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(
                Query.query(Criteria.where("_id").is("5d35ca91632f763b48917fa2")));
        //打开下载流对象
        GridFSDownloadStream fsDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsResource,用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,fsDownloadStream) ;
        // 获取流中的数据
        String content = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");
        System.out.println(content);
    }

结果:
在这里插入图片描述

删除文件

//删除文件 
    @Test
    public void testDelFile() throws IOException {
        //根据文件id删除fs.files和fs.chunks中的记录 
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92")));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值