Ghazanfar Idrees
Ghazanfar Idrees

Reputation: 31

save base64 image from javascript

I have a variable in JavaScript name as myImage which holds the base64 encoded string of an image like data:image/png;base64,iVBORw0KGgoAAAANSUhE...... Now I want to save this image on folder at server side. Please Help

Thanks in Advance

Upvotes: 0

Views: 6462

Answers (2)

PDHide
PDHide

Reputation: 19929

The below code does the trick:

Here you are just writing the data to a file and saving it in the write format

var data = image.replace(/^data:image\/\w+;base64,/, "");
    var buf = new Buffer(data, 'base64');
    fs.writeFile('image.png', buf,function(err, result) {
      if(err){console.log('error', err);}
    });

The resulting image will be stored as image.png at the current directory

Upvotes: 2

Zachrip
Zachrip

Reputation: 3382

You need to work on asking questions a little better, but I will try to give you a basic explanation.

Step one: Pass the base64 string to the server.

Step two: Strip the first parts and last parts.

Step three: base64_decode the string.

Step four: file_put_contents the result of that.

Of course this is very basic, but there are already answers out there for this, and I was able to find even more with a google search.

Upvotes: 4

Related Questions