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

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

    @RequestMapping(value = "/api ")
    public class AttachmentController {
    
    private final GridFsOperations gridFsOperations;
    
    @Autowired
    public AttachmentController(GridFsOperations gridFsOperations) {
        this.gridFsOperations = gridFsOperations;
    }
    
    @GetMapping("/file/{fileId}")
    public ResponseEntity getFile(@PathVariable String fileId) {
    GridFSFile file = 
    gridFsOperations.findOne(Query.query(Criteria.where("_id").is(fileId)));
    
        return ResponseEntity.ok()
                .contentLength(file.getLength())
                .body(gridFsOperations.getResource(file));
    }
    

提交回复
热议问题