【MongoDB】GridFS入門

一、介紹

GridFS是MongoDB提供的用於持久化存儲文件的模塊,CMS使用MongoDB存儲數據,使用GridFS可以快速集成 開發。 它的工作原理是: 在GridFS存儲文件是將文件分塊存儲,文件會按照256KB的大小分割成多個塊進行存儲,GridFS使用兩個集合 (collection)存儲文件,一個集合是chunks, 用於存儲文件的二進制數據;一個集合是files,用於存儲文件的元數 據信息(文件名稱、塊大小、上傳時間等信息)。 從GridFS中讀取文件要對文件的各各塊進行組裝、合併。
詳細參考:https://docs.mongodb.com/manual/core/gridfs/

二、實例

1、GridFS存取文件測試

1、存文件

使用GridFsTemplate存儲文件測試代碼:
向測試程序注入GridFsTemplate。

@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {

    @Autowired
    GridFsTemplate gridFsTemplate;

    /**
     * 存文件
     */
    @Test
    public void testGridFsSaveFile() throws FileNotFoundException {

        //要存儲的文件
        File file = new File("e:/index_banner.ftl");
        // 定義輸入流
        FileInputStream inputStram = new FileInputStream(file);
        // 向GridFS存儲文件
        ObjectId objectId = gridFsTemplate.store(inputStram, "輪播圖測試文件01", "");
        // 得到文件ID
        String fileId = objectId.toString();
        System.out.println(file);
    }
}

存儲原理說明:
文件存儲成功得到一個文件id
此文件id是fs.files集合中的主鍵。
可以通過文件id查詢fs.chunks表中的記錄,得到文件的內容。

2、讀取文件

1)在config包中定義Mongodb的配置類,
如下: GridFSBucket用於打開下載流對象

/**
 * @author 麥客子
 * @desc  Mongodb的配置類
 * @email [email protected]
 * @create 2019/07/17 21:53
 **/
@Configuration
public class MongoConfig {

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

    /**
     * GridFSBucket用於打開下載流對象
     * @param mongoClient
     * @return
     */
    @Bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient) {
        MongoDatabase database = mongoClient.getDatabase(db);
        GridFSBucket bucket = GridFSBuckets.create(database);
        return bucket;
    }
}

測試代碼:

@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {

    @Autowired
    GridFsTemplate gridFsTemplate;

    @Autowired
    GridFSBucket gridFSBucket;

    /**
     * 讀取文件
     * @throws IOException
     */
    @Test
    public void queryFile() throws IOException {

        String fileId = "5d2f261dd8d5cf41c0465db3";
        // 根據id查詢文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
        // 打開下載流對象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        // 創建gridFsResource,用於獲取流對象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        // 獲取流中的數據
        String s = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");
        System.out.println(s);
    }
 }

3、刪除文件

    /**
     * 刪除文件 
     * @throws IOException
     */
    @Test
    public void testDelFile() throws IOException {
        //根據文件id刪除fs.files和fs.chunks中的記錄 			  
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5d2f261dd8d5cf41c0465db3")));
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章