Node: Writing a base64 source to an image file

So I'm working on a node app with a file input that uses client side js to get the base64 dataURI code from an image and send it to the server as a socket message.

the resultant base64 message is in the format:

data:image/jpeg;base64,/9j/4QCcRXhpZgAASUkqAAgAAAA ... 

On the node/server side, I want to save this message as an image file:

    fs.writeFile(newFilePath, src, function (err) {
      if (err) throw err;
      console.log('It\'s saved! ' + entryID + '.' + fileType + '\n');
      socket.emit('sendFileSuccess', entryID + '\n');
    });

After running, the file does save to the right location with a similar file size. But the file isn't a valid image when I open it up with preview ("It may be damaged or use a file format that Preview doesn’t recognize.")

I'm looking for the minimum solution, and I'd plan to add any required complexity later.

Thanks!

Answers


You need to take out the data:image/jpeg;base64, part.

var data = src.replace(/^data:image\/png;base64,/,'');

fs.writeFile(newFilePath, data, 'base64', function(err) {
  if (err) throw err;
  console.log('It\'s saved! ' + entryID + '.' + fileType + '\n');
  socket.emit('sendFileSuccess', entryID + '\n');
});

You need to convert the image back to binary format if you want to store it on your server as a proper image file. To do this you need to parse and remove the base64 header "data:image/jpeg;base64,", create a Buffer with encoding set to "base64" and store it in the filesystem with the apropiate file extension parsed from the header.


Need Your Help

many small sized functions

c optimization compiler-construction

in computer literature it is generally recommended to write short functions as much as possible. I understand it may increase readability (although not always), and such approach also provides more

Laziness and tail recursion in Haskell, why is this crashing?

performance optimization haskell lazy-evaluation ghc

I have this fairly simple function to compute the mean of elements of a big list, using two accumulators to hold the sum so far and the count so far: