重写GridFsTemplate类, MongoDB文件库实现同名文件共存 顶

时间:2022-06-09
本文章向大家介绍重写GridFsTemplate类, MongoDB文件库实现同名文件共存 顶 ,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在MongoDB库中使用GridFsTemplate给基于Spring Boot的项目在进行文件的存储和读取操作提供了很大的便利,但是在使用过程中要获取MongDB库内文件的InputStream时,却仅有如下方法获取:

public GridFsResource getResource(String location) {
    GridFSFile file = findOne(query(whereFilename().is(location)));
    return file != null ? new GridFsResource(file, getGridFs().openDownloadStream(location)) : null;
}

这种方法的好处是在库内不存在多个同名文件时可以通过简单的文件名获取到文件的InputStream进行下载操作,但是在一个共享库规模大,出现多个同名不同内容的文件时,以上方法就存在局限性了,因此通过重写GridFsTemplate类的以上方法,可以简单的实现单库内多个同名文件的区别存储和读取操作,简要示例代码如下:

@Component
public class GridFsAssistant {

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

    private final MongoClient mongoClient;

    @Autowired
    public GridFsAssistant(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    public MongoDatabase getMongoDB(String databaseName) {
        return mongoClient.getDatabase(databaseName);
    }

    public MongoDatabase getDefaultMongoDB() {
        return getMongoDB(database);
    }

    public GridFSDownloadStream getResource(ObjectId storedId) {
        GridFSBucket gridFSBucket = GridFSBuckets.create(getDefaultMongoDB());
        MongoCollection<Document> coll = getDefaultMongoDB().getCollection("fs.files");
        FindIterable<Document> file = coll.find(eq("_id", storedId));
        return file.first() != null ? gridFSBucket.openDownloadStream(storedId) : null;
    }
}

以上是在使用GridFS进行MongDB文件存储及下载实现过程中发现的一个小问题,详细项目代码参见以下文档共享服务项目V0.1版本:

码云地址:https://gitee.com/mxleader/quick-doc-service

GitHub:     https://github.com/cbcgorilla/quick-doc-service