5

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 ?

Danny Varod
  • 17,324
  • 5
  • 69
  • 111
Louis
  • 418
  • 6
  • 22

3 Answers3

5

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 }}"> 
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Fathma Siddique
  • 266
  • 3
  • 15
0
exports.itemimage = function(req,res){
    gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
        res.contentType(file.contentType);
        // Check if image
        if (file) {
          // Read output to browser
          const readstream = gfs.createReadStream(file.filename);
          readstream.pipe(res);
        } else {
            console.log(err);
        }
    });
};
Joundill
  • 6,828
  • 12
  • 36
  • 50
Om Mo
  • 1
  • 1
0

i got the answer for that all you have to do is when you setup the route type the URL in the img src

app.get('/image/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
  return res.status(404).json({
    err: 'No file exists'
  });
}

// Check if image
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
  // Read output to browser
  const readstream = gfs.createReadStream(file.filename);
    readstream.pipe(res)
} else {
  res.status(404).json({
    err: 'Not an image'
  });
 }
});
});
and it worked
Mourad
  • 5
  • 4