如何将缓冲区转换为图像以显示在前端

问题描述 投票:0回答:1

我将图像作为 BLOB 数据类型保存在数据库中

我正在使用带有express的nodejs,并且我正在使用multer库来上传图像

   if (req.file) { userProfile.profilePhoto = req.file } await userProfile.save()

这就是我在前端所做的事情,我收到的个人资料照片为

    profilePhoto: { type: "Buffer", data: (15)[string of numbers] }

我尝试将其转换为base64,因为我查看了与此相关的其他问题,但对我来说不起作用,我在客户端完成了

     import {Buffer} from "buffer" const base64 = Buffer.from( result.data.profilePhoto.data, "binary" ).toString("base64");
这给了我一个像这样的奇怪字符串 W29iamVjdCBPYmplY3Rd

我想传递一个指向 src 属性的链接,我不知道如何做,任何帮助将不胜感激

我还应该在后端处理转换吗?什么是最好的

javascript node.js blob buffer
1个回答
0
投票

您的代码

import {Buffer} from "buffer" 
const base64 = Buffer.from(result.data.profilePhoto.data,
"binary" ).toString("base64");

将返回字符串“W29iamVjdCBPYmplY3Rd”。 添加

"data:image/png;base64,"
前缀...并将其添加到前端图像的 src 中..

也可以在后端进行相同的处理....

© www.soinside.com 2019 - 2024. All rights reserved.