【问题标题】:Store image in MongoDB and show it in React.js在 MongoDB 中存储图像并在 React.js 中显示
【发布时间】:2019-10-05 14:44:42
【问题描述】:

图像存储在 Mongo 中:

const Posts = new Schema({
    postImg: {
      data: Buffer,
      type: Buffer,
      contentType: String
    }
})

在数据库中的文档是这样的:

"postImg" : { "$binary" : "/9j/4AAQS.blaBla.long.binary.string.."}

当图像被提取到客户端时,它看起来像这样:

{data: Array(84106) [ 255, 216, 255, … ]
type: "Buffer"}

在这种情况下,图像应如下所示:

<img src={`data:image/png;base64,${props.postImg}`} alt="a"/>

但这不起作用,会显示alt。 我试过 {props.postImg.data},但还是没有。

有什么帮助吗?

附:我使用 node 和 express 用于服务器端,并使用 multer 包进行图像上传 ​

【问题讨论】:

    标签: reactjs mongodb image mongoose


    【解决方案1】:

    图像似乎是作为 node.js Buffer 类型获取的,然后将其编码为字节数组并发送到客户端。您需要在客户端上使用 base64 字符串。

    最简单的方法是在后端将缓冲区转换为 base64 字符串,然后将其发送给客户端。例如。

    const post = await getPostImgFromDatabase();
    res.send({
      ...post
      postImgBase64: Buffer.from(post.postImg).toString('base64')
    });
    

    然后在客户端:

    <img src={`data:image/png;base64,${props.postImgBase64}`} alt="a"/>
    

    【讨论】:

    • 谢谢 panta82,我也是这样做的。
    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 2016-10-27
    • 2012-09-14
    • 1970-01-01
    • 2021-05-20
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多