GridFS:如何在 <img/> 标签中显示 readstream.pipe(res) 的结果?

Lou*_*is 5 html png mongodb gridfs

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

\n
app.get("/images/profile/:uId", function (req, res) {\nlet uId = req.params.uId;\nconsole.log(uId)\ngfs.files.findOne(\n  {\n    "metadata.owner": uId,\n    "metadata.type": 'profile'\n  }\n  , function (err, file) {\n    if (err || !file) {\n      return res.status(404).send({ error: 'Image not found' });\n    }\n    var readstream = gfs.createReadStream({ filename: file.filename });\n    readstream.on("error", function (err) {\n      res.send("Image not found");\n    });\n    readstream.pipe(res);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

这会返回类似的内容:

\n
\xef\xbf\xbdPNG\n\n\nIHDR\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd]\xef\xbf\xbdbKGD\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xcc\xbf   pHYs\n\xef\xbf\xbd\n\xef\xbf\xbdB(\xef\xbf\xbdxtIME\xef\xbf\xbd  -u\xef\xbf\xbd\xef\xbf\xbd~IDATx\xef\xbf\xbd\xef\xbf\xbdi|TU\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdJDV\xef\xbf\xbdfH\xef\xbf\xbd0\xef\xbf\xbd :-\nH_\xef\xbf\xbd\xef\xbf\xbdM\xef\xbf\xbd\xef\xbf\xbd03`\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\n(\xef\xbf\xbd\xef\xbf\xbd-\xef\xbf\xbdq{U[\xef\xbf\xbdm\xef\xbf\xbdA\xef\xbf\xbd\xef\xbf\xbdAQ\xef\xbf\xbdVZ\xef\xbf\xbd\xd2\xa2bP\xef\xbf\xbd\xef\xbf\xbdS\xef\xbf\xbd@K@\xef\xbf\xbd\xef\xbf\xbdCB\xef\xbf\xbd\xef\xbf\xbd|\xef\xbf\xbd\xef\xbf\xbdT\xef\xbf\xbd[\xef\xbf\xbd=\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd"U\xef\xbf\xbd\xef\xbf\xbd[\xef\xbf\xbd\xef\xbf\xbd{\xef\xbf\xbds\xef\xbf\xbd9\xef\xbf\xbd  \n\xef\xbf\xbd+)@e\xdb\xbf\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd{\xef\xbf\xbd9\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd,?\xef\xbf\xbdT.S\xef\xbf\xbd\xef\xbf\xbdxL\xd6\x9fx&@\xef\xbf\xbd0TSFp7\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdt\xca\x81\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdA!_\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdD\xef\xbf\xbdh\xef\xbf\xbd \nz\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdod\xef\xbf\xbdG\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdYzV\xef\xbf\xbd?e\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd|\xef\xbf\xbdh\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd@P\xef\xbf\xbd,\xef\xbf\xbd{\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdZ\xef\xbf\xbdl\\vc\xef\xbf\xbdN\xd3\xb2\xef\xbf\xbd?\nn\xef\xbf\xbd\xef\xbf\xbd(\xef\xbf\xbdr\xef\xbf\xbd.......\n
Run Code Online (Sandbox Code Playgroud)\n

看来我正确地得到了 png 。那么如何在 img 标签中显示它呢?

\n

小智 5

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

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

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

  <img src="data:image/png;base64,{{ image }}" alt="{{ image }}"> 
Run Code Online (Sandbox Code Playgroud)