GridFS:如何在< img/>中显示readstream.pipe(res)的结果标签? [英] GridFS : How to display the result of readstream.pipe(res) in an <img/> tag?

查看:143
本文介绍了GridFS:如何在< img/>中显示readstream.pipe(res)的结果标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将MangoDB和GridFS一起使用来存储图像.我已经有了从数据库检索图像的方法:

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

这将返回类似的内容:

�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�.......

似乎我正确地获得了png.然后如何在img标签中显示它?

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

推荐答案

我已通过将块转换为base64字符串解决了该问题.然后,我将字符串传递如下:

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

这篇关于GridFS:如何在&lt; img/&gt;中显示readstream.pipe(res)的结果标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆