【问题标题】:GridFS : How to display the result of readstream.pipe(res) in an <img/> tag?GridFS:如何在 <img/> 标签中显示 readstream.pipe(res) 的结果?
【发布时间】:2018-05-11 20:16:50
【问题描述】:

我使用 MongoDB 和 GridFS 来存储图像。我有这条路线可以从数据库中检索图像:

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 标签中显示呢?

【问题讨论】:

  • 您可以在 html 中包含您的图片,例如:&lt;img src="/images/profile/9999" alt="" width="99" height="99"&gt;。您应该在 nodejs 的标头中设置Content-Type: image/png。
  • 啊,这很容易!谢谢:D

标签: html mongodb png gridfs


【解决方案1】:

我已经通过将块转换为 base64 字符串解决了这个问题。然后我传递了如下字符串:

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

我将把手中的值呈现如下:

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

【讨论】:

    【解决方案2】:

    我得到了答案 您所要做的就是在设置路由时在 img src 中输入 URL

    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'
      });
     }
    });
    });
    
    它奏效了

    【讨论】:

      【解决方案3】:
      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);
              }
          });
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-02
        • 2020-11-11
        • 1970-01-01
        • 2022-01-23
        • 2015-09-30
        • 1970-01-01
        • 2023-02-25
        相关资源
        最近更新 更多