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

前端 未结 10 1244
暗喜
暗喜 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:05

    There is a bit mess in these types:

    • GridFSFile is type from MongoDB driver
    • GridFsResource is type from Spring
    • ObjectId is type from BSON API

    From Spring GridFsTemplate source:

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

    There is an ugly solution:

    @Autowired
    private GridFsTemplate template;
    
    @Autowired
    private GridFsOperations operations;
    
    public InputStream loadResource(ObjectId id) throws IOException {
        GridFSFile file = template.findOne(query(where("_id").is(id)));
        GridFsResource resource = template.getResource(file.getFilename());
    
        GridFSFile file = operations.findOne(query(where("_id").is(id)));
        GridFsResource resource = operations.getResource(file.getFilename());
        return resource.getInputStream();
    }
    

提交回复
热议问题