GridFsTemplate 读取MongoDB 文件

转载自:https://www.codeleading.com/article/465773507/

叙述

GridFS是MongoDB提供的用于持久化存储文件的模块

GridFS将文件分块存储,文件会按照256KB的大小分割成多个块进行存储。GridFS存储文件用到了两个collection:一个是chunks,用来存储分块文件二进制数据;一个是files,用来存储文件信息(文件名称等信息)

解决方案

编写储存文件测试,这里返还存储文件id
此文件id是files集合中的主键
可以通过文件id查询chunks表中的记录,得到文件的内容

import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

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

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Test
    public void saveTest() throws FileNotFoundException {
        File file = new File("******");
        FileInputStream fis = new FileInputStream(file);
        ObjectId objectId = gridFsTemplate.store(fis, "***");
        //打印文件id
        System.out.println(objectId.toString());
    }

}

读取文件:

配置mongoDB bucket

@Configuration
public class MongoDBConfig {

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

    @Bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient){
        //得到mongodb数据库
        MongoDatabase database = mongoClient.getDatabase(db);
        //返回bucket
        return GridFSBuckets.create(database);
    }
}

测试读取文件

@Test
public void getTest() throws IOException {
    //根据文件id查询数据库
    GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("******")));
    //打开下载流对象
    GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
    //获取流对象
    GridFsResource gridFsResource = new GridFsResource(gridFSFile, downloadStream);
    //得到有数据流
    InputStream inputStream = gridFsResource.getInputStream();
}

 

你可能感兴趣的:(Spring相关)