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

前端 未结 10 1246
暗喜
暗喜 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条回答
  •  -上瘾入骨i
    2021-02-02 15:15

    getResource(com.mongodb.client.gridfs.model.GridFSFile file) function of GridFsTemplate returns the GridFsResource for a GridFSFile.

    GridFSFile gridfsFile= gridFsTemplate.findOne(new 
    Query(Criteria.where("filename").is(fileName)));
    GridFsResource gridFSResource= gridFsTemplate.getResource(gridfsFile);
    InputStream inputStream= gridFSResource.getInputStream();
    

    If the above one is not working in some higher version of Spring boot, use the bellow:

    GridFSFile gridfsFile= gridFsTemplate.findOne(new 
    Query(Criteria.where("filename").is(fileName)));
    //or
    GridFSFile  gridfsFile = 
    gridFsOperations.findOne(Query.query(Criteria.where("filename").is(fileName)));
     return ResponseEntity.ok()
                    .contentLength(gridFsdbFile.getLength())
                    .contentType(MediaType.valueOf("image/png"))
                    .body(gridFsOperations.getResource(gridFsdbFile));
    

提交回复
热议问题