Search code examples
htmlmongodbpnggridfs

GridFS : How to display the result of readstream.pipe(res) in an <img/> tag?


I am using MongoDB along with GridFS to store images. I've got this route to retrieve an image from the DB :

app.get("/images/profile/:uId", function (req, res) {
let uId = req.params.uId;
console.log(uId)
gfs.files.findOne(
  {
    "metadata.owner": uId,
    "metadata.type": 'profile'
  }
  , function (err, file) {
    if (err || !file) {
      return res.status(404).send({ error: 'Image not found' });
    }
    var readstream = gfs.createReadStream({ filename: file.filename });
    readstream.on("error", function (err) {
      res.send("Image not found");
    });
    readstream.pipe(res);
  });
});

This returns something like that :

�PNG


IHDR���]�bKGD���̿   pHYs
�
�B(�xtIME�  -u��~IDATx��i|TU����JDV�fH�0� :-
H_��M��03`���
(��-�q{U[�m�A��AQ�VZ�ҢbP��S�@K@��CB��|��T�[�=����"U��[��{�s�9�  
�+)@eۿ���{�9���,?�T.S��xL֟x&@�0TSFp7���tʁ���A!_����D�h� 
z����od�G���YzV�?e���|�h���@P�,�{�������Z�l\vc�NӲ�?
n��(�r�.......

It seems like I get the png correctly. How do I display it in an img tag then ?


Solution

  • I have solved the issue by converting the chunk into base64 string. I then passed the string as below:

      const readstream = gfs.createReadStream(file.filename);
      readstream.on('data', (chunk) => {
        res.render('newHandlebarFile', { image: chunk.toString('base64') });
      })
    

    I render the value in handlebars as below:

      <img src="data:image/png;base64,{{ image }}" alt="{{ image }}">