将图片存储在MongoDB中并在React.js中显示它

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

图像存储在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},但还是没有。

有帮助吗?

P.S。我将node和express用于服务器端,并将multer包用于图像上传

reactjs mongodb image mongoose
1个回答
0
投票

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

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