dani
dani

Reputation: 43

GridFSDBFile in spring boot 2.0.1 release

I am trying to migrate spring boot 1.5.7 to its latest version realease 2.0.1. In the old version I used this syntax to recover a file.

GridFSDBFile gridFsdbFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(fileId)));

Do you know how it would be done in the new version? I need

file.setInputStream(gridFsdbFile.getInputStream());

ty!

Upvotes: 3

Views: 3861

Answers (3)

iarik
iarik

Reputation: 61

GridFSFile gridFsdbFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));

GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFsdbFile.getObjectId());
GridFsResource gridFsResource = new GridFsResource(gridFsdbFile,gridFSDownloadStream );

then

file.setInputStream(gridFsResource.getInputStream());

You can define gridFSBucket in MongoConfiguration like this

@Bean public GridFSBucket getGridFSBuckets() {
MongoDatabase db = mongoDbFactory().getDb();
return GridFSBuckets.create(db);
}

Upvotes: 4

Vitaljok
Vitaljok

Reputation: 623

Seems that since Spring Boot 2.0.x GridFS operations are mowing towards Resource approach.

Given you have unique file names in your GridFS, you can do like this:

gridFsTemplate.getResource("my-file-name.txt")

Any arbitary ID can be used instead of real file name to ensure its uniqueness when storing the file (e.g. ObjectId).

gridFsTemplate.store(inputStream, "5a55f1ea29485119f7a671a7")

Also there is commit in 2.1.0.M3 with helper method for getting resource by GridFSFile, but under the hood it still uses file name.


In order to get file content by pure ID you can use something like this:

GridFSBuckets.create(dbFactory.getDb()).openDownloadStream(gridFsFileId)

Upvotes: 1

dani
dani

Reputation: 43

a temporary solution to leave it the same is to include the dependency

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.10.11.RELEASE</version>
</dependency>

https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb/1.10.11.RELEASE

Upvotes: 0

Related Questions