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

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

    i discovered the solution to this problem!

    Just wrap the GridFSFile in a GridFsResource! This is designed to be instantiated with a GridFSFile.

    public GridFsResource getUploadedFileResource(String id) {
        var file = this.gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
        return new GridFsResource(file);
    }
    
    @GetMapping("/{userId}/files/{id}")
    public ResponseEntity getUploadedFile(
        @PathVariable Long userId,
        @PathVariable String id
    ){
        var user = userService
            .getCurrentUser()
            .orElseThrow(EntityNotFoundException::new);
    
        var resource = userService.getUploadedFileResource(id);
    
        try {
            return ResponseEntity
                .ok()
                .contentType(MediaType.parseMediaType(resource.getContentType()))
                .contentLength(resource.contentLength())
                .body(resource);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    
    
    }
    

    The great advantage of this is, that you can directly pass the GridFsResource to a ResponseEntity due to the fact, that the GridFsResource extends a InputStreamResource.

    Hope this helps!

    Greetings Niklas

提交回复
热议问题