Reputation: 87
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?
Upvotes: 0
Views: 891
Reputation: 87
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'
}
}
Upvotes: 1