$a �$I�"I�$... 用于 PNG 图像 - Vue/Node/Express | 如何显示从 Node.js 服务器发送到客户端 Vue 应用程序的图像?

$�a �$I��"I�$�... for PNG image - Vue/Node/Express | How do I display an image that I sent from a Node.js server to a client Vue app?

使用Node/Express,我有以下路线:

app.get('/get-image', function(req, res) {

  ...
  
  
  res.sendFile(path.join(__dirname, '..', account.profileImg));
})

在我的客户端 Vue 应用程序中,我试图显示我从服务器接收到的图像。目前我正在将文件发送到控制台,但我得到了这些奇怪的字符:

04f\u0001����@7��\u000f�T�n����_��\u0004\f\u0002# ....等等...很长的字符串

header 表示它是类型 "content-type : "image/png"“这很好,因为我正在尝试显示图像。

我需要做什么才能将此字符串转换为可视图像?我可以以 HTML 标签的形式传递给我的 Vue 组件。

方向正确的任何 tips/advice 都会非常有帮助!

04f\u0001���@7�\u000f�T�n���_�\u0004\f\u0002#

一种方法是使用 btoa 将图像数据作为 base64 编码字符串发送,使用响应中的编码字符串设置图像的 src 属性:

<img src=`data:image/png;base64,${data}`/>

否则,您也可以return Express 的回复图片,例如:

let image = new Buffer(imageData, 'base64');

res.writeHead(200, {
  'Content-Type': 'image/png',
  'Content-Length': image.length
});
res.end(image);