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