You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从JSON中提取base64编码图片字符串时返回乱码的问题咨询

问题原因

MongoDB 中存储的 img.data 为 Buffer 二进制类型,Express 的 res.send 方法接收到 Buffer 类型参数时,会默认将其作为二进制流返回,因此 Postman 会将内容识别为二进制数据,显示为乱码。

解决方案

将 Buffer 对象手动转换为 Base64 编码的字符串后再返回即可,修改后的接口代码如下:

app.post("/getImage", (req, res)=>{
   User.findOne({ login: "name" })
     .then((user) => {
        // 把Buffer类型转换为base64字符串
        const imageBase64 = user.img.data.toString('base64')
        res.send(imageBase64)
     })
     .catch((error) => {
       console.log(error);
       // 原代码的res.send(500)不符合Express规范,替换为sendStatus
       res.sendStatus(500)
     });
})

补充说明

如果前端需要直接使用该字符串渲染图片,可以在返回时拼接对应图片格式的 MIME 前缀,示例如下:

// 以png格式为例,可根据实际存储的图片类型调整
const fullBase64 = `data:image/png;base64,${imageBase64}`
res.send(fullBase64)

前端拿到完整字符串后可直接赋值给 <img> 标签的 src 属性使用。

内容的提问来源于stack exchange,提问作者King Of Chads

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:09:03