Perhaps you are trying to save a file with metadata. therefore make base64 decoded data invalid.
Here is what I mean:
data:image/png;base64,iVBORw0KG....
Data: image / png; base64 is just meta and is not encoded using base64, so:
You need to separate it from the bite, then decode, and then save to disk.
I use this convenient function:
function decodeBase64Image(dataString) { var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), response = {}; if (matches.length !== 3) { return new Error('Invalid input string'); } response.type = matches[1]; response.data = new Buffer(matches[2], 'base64'); return response; }
source: NodeJS write base64 image file
So edit how I use it:
var decodedImg = decodeBase64Image(imgB64Data); var imageBuffer = decodedImg.data; var type = decodedImg.type; var extension = mime.extension(type); var fileName = "image." + extension; try{ fs.writeFileSync(".tmp/uploads/" + fileName, imageBuffer, 'utf8'); } catch(err){ console.error(err) }
Where mime is a great node-mime lib. npm install mime.
source share