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")));
}
发布了243 篇原创文章 · 获赞 87 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/IT_10/article/details/103945380