0

Image is stored in Mongo:

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

In database document looks like this:

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

And when image is fetched to the client, it looks like this:

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

In this case images should be shown like this:

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

But that won't work, alt gets shown. I tried {props.postImg.data}, but still nothing.

Any help?

P.S. I use node and express for server-side, and multer package for image upload ​

1 Answer 1

2

The image seems to be fetched as a node.js Buffer type, which is then encoded as an array of bytes and sent to client. You need base64 string on the client.

The easiest way to get there would be to convert buffer to base64 string on your backend, and then send that to client. Eg.

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

Then on client:

<img src={`data:image/png;base64,${props.postImgBase64}`} alt="a"/>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you panta82, I did it in similar way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.