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
.
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();