Pono
Pono

Reputation: 11776

Node.js: How to save base64 encoded images on server as png/jpg

I send from client to server a PNG as a base64 string. I decode it back and save to server. But the file is not readable as a png. Do I have to add specific headers? What am I doing wrong? Here's my code:

var base = decodedBase64;
fs.writeFile("/tmp/test.png", base, function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log("The file was saved!");
  }
});

Upvotes: 3

Views: 5508

Answers (1)

Raynos
Raynos

Reputation: 169391

fs.writeFile("/tmp/test.png", base, "binary", function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log("The file was saved!");
  }
});

The default encoding is utf-8. You don't want to save it as text, you want to safe it as binary data so pass in the binary encoding.

Upvotes: 7

Related Questions