nobody
nobody

Reputation: 414

NodeJS write base64 encoded image to file

I have searched and tried all of the solutions at stackoverflow but none of them seems working at my instance. Basically I have an image, edited by html5 canvas, upload from client and I need to save it to disk, but unfortunately I can't open the file that I just saved. (I am using Windows 7)

My code:

var base64Data = req.body.image.replace(/^data:image\/(png|gif|jpeg);base64,/,'');
require('fs').writeFile('public/aboutToGiveUp.png', new Buffer(base64Data, 'base64'));

Upvotes: 3

Views: 2049

Answers (2)

nrs jayaram
nrs jayaram

Reputation: 3438

Got same bug, it's because of incorrect url path, You may added app.use("/", express.static(path.join(__dirname, 'public')));, so no need to add the public in the url, check your url path once.

working sample :

  • url = req.protocol+'://'+req.headers.host+"/"+filename;

  • url = req.protocol+'://'+req.headers.host+"/images/"+filename; // its in public/images

Upvotes: 1

shikhar
shikhar

Reputation: 2469

Try using ./public/aboutToGiveUp.png or make sure that the path is relative to the file containing this code.

Upvotes: 0

Related Questions