0

I am making a nodejs app which displays pictures stored on servers ,I was using multer to store pictures in the same directory and I was using mongodb as my database to store the path of the picture that user uploads , and then i read the path and displayed the pictures something like this,

<div class="post-image flex">
        <%var imagesource='../'+postobj.blob.path%>
        <div>
            <img class='onbottomimage' src="<%=imagesource%>" >
        </div>
</div>

everything was working fine locally. but now I have deployed my app to heroku and found out I cannot store pictures on heroku as the user uploads them, I still have the pictures stored in mongodb in base 64 format something like this

image
:
Binary('/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+EUI0V4aWYAAE1NACoAAAAIAAcBMgACAAAAFAAAAGIBOwACAAAA...', 0)

how do i convert them back to pictures and display them in img tag in ejs, or what other options do i have ,I dont want to change heroku but still be able to display the pictures that the user uploads.

Nikhil Singh
  • 353
  • 1
  • 17
  • This should help https://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file – prabhu Jul 17 '20 at 17:29
  • @prabhu i had read this one but, as I said I cannot store images on heroku fs.writefile wont work here – Nikhil Singh Jul 17 '20 at 17:31
  • This can help you also. https://stackoverflow.com/questions/43503963/retrieving-images-stored-in-mongodb-with-nodejs – Mateus Leonardi Jul 17 '20 at 17:32
  • @NikhilSingh In that case you'll have to decode the bas64 image every time the user requests for it, not exactly efficient or scalable. Any case this is what you are looking for https://stackoverflow.com/a/21227124/2098386 – prabhu Jul 17 '20 at 17:45

2 Answers2

1

If you are storing your uploaded images in the Heroku server, it is an utter waste. Because Heroku Dyno will restart every day which will delete all the extra added data other than data stored during deployment time. I think you are using express.

let fs=require("fs")
let yourBuffer=//retrieve that buffer and store into this(yourBuffer) variable
let buffer = new Buffer.from(yourBuffer)
fs.writeFile(`location to storeimage/imagename.yourimageextension`, buffer, "binary", function (err, written) {
    if (err) console.log(err);
    else {
        console.log("Successfully written");
        res.sendFile((__dirname + `location of image/imagename.yourimageextension`))
    }
});
Nithin K Joy
  • 943
  • 8
  • 14
0

I think a better solution would be using a 3rd party storage provider, aws s3 for example, and only store image url in the database

Neoflies
  • 263
  • 1
  • 3
  • 7