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

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

    Spring Data 2.1.0 added an overload of getResource() to GridFsTemplate that returns the GridFsResource for a given GridFsFile. GridFsResource has a method to get the InputStream. Therefore, if you're on at least this version of Spring Data, you can get the InputStream by making two calls to the GridFsTemplate:

    GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
    
    // In real code, make sure you perform any necessary null checks if the file doesn't exist
    
    GridFsResource resource = gridFsTemplate.getResource(gridFsFile);
    InputStream inputStream = resource.getInputStream();
    

提交回复
热议问题