N.Fern
N.Fern

Reputation: 11

How do I write a GridFSFile object into a ByteArrayOutputStream object?

There was an easy way to do it with gridFSDBFile, but not anymore.

//This used to return a GridFSDBFile type. Returns GridFSFile now.
GridFSFile gridFsFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(idTemp)));
//And would be done this way. Not anymore.
gridFSFile.writeTo(outputstream)

The main goal is to return an image saved in the database to display it on an html page as follows.

response.getOutputStream().write(outputstream.toByteArray());
response.getOutputStream().close();

Upvotes: 1

Views: 1181

Answers (2)

Vasanth Umapathy
Vasanth Umapathy

Reputation: 1741

I have got the same issue while migrating spring 1.x to 2.x. Here is the fix.

InputStream iStream =  gridFsTemplate.getResource(gridFSFile).getInputStream();

byte[] bytes = IOUtils.toByteArray(iStream);

Upvotes: 1

Babyburger
Babyburger

Reputation: 1828

I am probably late, but you can chain an InputStream to OutputStream.

So you can use the following:

GridFSFile gridFsFile = gridFsTemplate.findOne(...);
gridFsTemplate.getResource(gridFsFile).getInputStream().transferTo(outputStream);

Upvotes: 0

Related Questions