GridFS持久化文件到MongoDB

GridFS是MongoDB提供的用於持久化存儲文件的模塊。GridFS存儲文件是將文件分塊存儲,文件會按照256KB的大小分割成多個塊進行存儲,GridFS使用兩個集合(collection)存儲文件,一個集合是chunks, 用於存儲文件的二進制數據;一個集合是files,用於存儲文件的元數據信息(文件名稱、塊大小、上傳時間等信息)。

GridFS存取文件示例

需要的依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

配置mongodb application.yml:

spring:
  data:
    mongodb:
      uri:  mongodb://localhost:27017
      database: test

mongodb中需要有這兩個集合:
在這裏插入圖片描述

存儲文件

test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
test
</div>
</body>
</html>

測試類:

@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {
    @Autowired
    GridFsTemplate gridFsTemplate;

    //存文件
    @Test
    public void testStore() throws FileNotFoundException {
        //定義file
        File file =new File("d:/test.ftl");
        //定義fileInputStream
        FileInputStream fileInputStream = new FileInputStream(file);
        ObjectId objectId = gridFsTemplate.store(fileInputStream, "test.ftl");
        System.out.println(objectId);
    }
}

在這裏插入圖片描述

輸出的是文件id:5e1abbf2d7505b046c08c051,即fs.files中的主鍵id,查看fs.files集合:
在這裏插入圖片描述
fs.chunks中的數據:
在這裏插入圖片描述
5e1abbf2d7505b046c08c051對應的就是fs.files的id,如果文件較大,會分成多個文檔。

讀取文件

GridFSBucket用於打開下載流對象

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

    @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;

    //取文件
    @Test
    public void queryFile() throws IOException {
        //根據文件id查詢文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5e1abbf2d7505b046c08c051")));

        //打開一個下載流對象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //創建GridFsResource對象,獲取流
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
        //從流中取數據,IOUtils是Apache提供的一個IO讀取工具類
        String content = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");
        System.out.println(content);
    }
}

輸出:
在這裏插入圖片描述

刪除文件

public void testDelFile() throws IOException {
	//根據文件id刪除fs.files和fs.chunks中的記錄
	gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5e1abbf2d7505b046c08c051")));
}
發佈了261 篇原創文章 · 獲贊 102 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章