How to get a binary stream by GridFS ObjectId with Spring Data MongoDB

前端 未结 10 1248
暗喜
暗喜 2021-02-02 15:00

I can\'t figure out how to stream a binary file from GridFS with spring-data-mongodb and its GridFSTemplate when I already have the right ObjectId.

10条回答
  •  梦如初夏
    2021-02-02 15:17

    I stumbled upon this, too. And I am actually pretty shocked that the GridFsTemplate has been designed like this... Anyway, my ugly "solution" to this so far:

    public GridFsResource download(String fileId) {
        GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
    
        return new GridFsResource(file, getGridFs().openDownloadStream(file.getObjectId()));
    }
    
    private GridFSBucket getGridFs() {
    
        MongoDatabase db = mongoDbFactory.getDb();
        return GridFSBuckets.create(db);
    }
    

    Note: You have to inject the MongoDbFactory for this to work...

提交回复
热议问题