Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在MongoDB中存储图像并在React.js中显示_Reactjs_Mongodb_Image_Mongoose - Fatal编程技术网

Reactjs 在MongoDB中存储图像并在React.js中显示

Reactjs 在MongoDB中存储图像并在React.js中显示,reactjs,mongodb,image,mongoose,Reactjs,Mongodb,Image,Mongoose,图像存储在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,

图像存储在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"/>
当图像被提取到客户端时,它如下所示:

"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"/>
在这种情况下,图像应如下所示:

"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包进行图像上传

图像似乎是作为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"/>

图像似乎以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,我也是这样做的。谢谢panta82,我也是这样做的。