0

Terminal Output

I am trying to get an image stored in my mongodb database to be retrieved and rendered to the browser. I have already tried some previous solutions such as btoa, window.btoa, but it says both are not defined. (https://stackoverflow.com/questions/6182315/how-to-do-base64-encoding-in-node-js)(https://stackoverflow.com/questions/23097928/node-js-throws-btoa-is-not-defined-error)

My current code looks like:

<img src= <%= `data:${event.eventImage.mimetype};base64,` + Buffer.from(`${event.eventImage.file}`, 'binary').toString('base64') %> >

Which results in the output in the link above. The binary has alot of '/' in it which I don't think should be there. How do I convert the binary properly so my image will render?

JSFiddle

Yates
  • 87
  • 2
  • 7
  • You can use base 64 data directly in your img src attribute, this answer explains how [How to display Base64 images in HTML?](https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html) – Nino Filiu Apr 19 '20 at 18:10
  • @NinoFiliu I had also looked at that page as well. I even copied and pasted my whole base64 string (shown in the Terminal Output link above) into the jsfiddle example and it still did not render my image. It's something wrong with the binary to base64 itself but I'm not sure what's wrong... – Yates Apr 19 '20 at 18:20
  • Why would you do it this way? Simply serve the actual binary for your image from your Node.js server. In your HTML, reference the URL of your Node.js server. It's crazy to add 33% overhead in storage, extra overhead in memory and CPU, for zero benefit and all the size restrictions, the way you're doing it now. – Brad Apr 19 '20 at 18:23
  • @Brad I'm not really sure what you mean. I'm using a route in Nodejs, using mongoose to get the file from mongodb, then rendering it to the view with ejs... I'm running this all locally, except the db is on Mongodb Atlas. – Yates Apr 19 '20 at 18:32
  • @Yates Set up a route like `/images/:id`, then in your HTML use ``. Decouple the HTML from the images. Then, in your route for the image, you can fetch the image from your database and serve it up as an image. – Brad Apr 19 '20 at 18:33
  • @Brad. Thank you so much. It actually works now XDDD – Yates Apr 19 '20 at 19:15

1 Answers1

1

I ended up doing as @Brad suggested. In my view I wrote:

<img src='http://localhost:3000/public/images/<%=event._id %>' >

I then created a route in Nodejs to handle /images/:id.

router.get('/images/:id', function(req,res){
LCEvent.findById(req.params.id)
    .exec()
    .then(doc =>{
        res.send(doc.eventImage.file);
    })
    .catch(err => console.log(err));
})

In my case my document was structured as

{
     eventImage: { 
        file: Binary {...}, 
        filename: 'dreamlifestyle.jpg', 
        mimetype: 'image/jpeg'
    }
}
Yates
  • 87
  • 2
  • 7