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")));
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章