0

I am storing images in MongoDB as base64 string. I created Express route to get image by id:

router.get('/:userId/images/:imgId', (req, res) => {
  Image.findOne(
    { _id: req.params.imgId },
    (err, img) => {
      if (err) {
        res.status(500).send('someErr');
      } else {
        var resultImg = Buffer.from(img.data, 'base64');
        res.writeHead(200, {
          'Content-Type': 'image/png',
          'Content-Length': resultImg.length
        });
        res.end(resultImg);
      }
    }
  );
});

Client-side:

<img src={`api/users/${userId}/images/${imgId}`} />

What I am sure about:

  1. path is correct, server receives request and returns 200 response
  2. data is correctly fetched from MongoDB
  3. base64 string is correct (when I copy paste to verifier like https://codebeautify.org/base64-to-image-converter, it is working)

Why images are not loaded?

4
  • try changing res.end(resultImg) to res.end(resultImg, 'binary'); Commented Sep 23, 2018 at 18:13
  • @Amirmasudzarebidaki it doesn't help Commented Sep 23, 2018 at 18:18
  • Have you seen this answer? Doesn't it helped? Commented Sep 23, 2018 at 18:46
  • did you ever get this to work? Commented Mar 14, 2019 at 12:42

2 Answers 2

1

make sure the output has this string at the beginning

<img src='data:image/png;base64,your base 64 goes here'/>

you can test by copying the output and put it in a static html and see does it work. so may be something like this would help

<img src=`data:image/png;base64,{`api/users/${userId}/images/${imgId}`}`/>
Sign up to request clarification or add additional context in comments.

Comments

-1

Have you try hit your backend using AJAX or Fetch API ? After that, you can load response from that API into your image element

1 Comment

You can check this gist here

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.