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

≯℡__Kan透↙ 提交于 2019-12-24 06:32:10

问题


I am using MangoDB 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 ?


回答1:


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 }}"> 



回答2:


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);
    }
});

};



来源:https://stackoverflow.com/questions/47530471/gridfs-how-to-display-the-result-of-readstream-piperes-in-an-img-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!