1

I uploaded an image to mongoose and the it was saved as a binary data like so:

enter image description here

Now Im trying to retrieve that image and display within my HTML page like so:

 <img id="user-img" src="data:image/png;base64, {{base64String}}">

I have tried the following:

I am trying to convert the binary image server side before sending the user all the data.

let getOne = (req, res) => {
  User.findById(req.params.id)
    .exec()
    .then((data) => {
        if (data) {
            data.photo = new Buffer(data.photo.toString(), 'base64');
             sendJsonResponse(res, 200, data)
        } else if (!data) {
            sendJsonResponse(res, 404, {"message": "Unable to find a single user"})
        }
    })
    .catch(err => {
        sendJsonResponse(res, 500, err)
    })
  };

At this point the server crashes and gives a Internal Server Error 500

What am I doing wrong?

Update:

enter image description here

Update:

enter image description here

Skywalker
  • 4,984
  • 16
  • 57
  • 122
  • @RolandStarke see updated question for an image of the error received. – Skywalker Jan 24 '18 at 17:32
  • @RolandStarke hi, please see updated question for console logged error. – Skywalker Jan 24 '18 at 17:37
  • Ah okay. so photo is not defined. don't as me why :D – Roland Starke Jan 24 '18 at 17:38
  • When you got your photo you can get rid of `new Buffer(data.photo.toString(), 'base64');` I assume photo is already a buffer so: `var base64OfPhoto = data.photo.toString('base64')` is enough. – Roland Starke Jan 24 '18 at 17:47
  • @RolandStarke thanks. I’ll try that now. I noticed something weird though. I uploaded a new image to mongoose and now it’s returning the image in base64 automatically. This has happened before as well. After a while it starts returning binary data instead of base64. Any idea why? – Skywalker Jan 24 '18 at 17:53
  • maybe your old images where saved differently? Else maybe `data.photo = ` has no effect like described here: https://stackoverflow.com/a/14510823/5378743 – Roland Starke Jan 24 '18 at 18:01
  • @RolandStarke apologies for the late reply. The weird thing is both times the data was saved exactly the same way. I just uploaded another image and now it’s returning pure base64 string. – Skywalker Jan 24 '18 at 19:15

1 Answers1

0

There is no need for the .exec() part. The exec runs and returns the data but then is expecting a promise.

User.findById(req.params.id)
    .then((data) => {

Should work.

David Newcomb
  • 10,639
  • 3
  • 49
  • 62