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

Warning when using Reachability.h

iphone objective-c

When using Reachability.h — Apple's code to deal with connections on iOS:

What's a good SVN service?

svn version-control

I'm considering shopping for SVN services. There's only 2 developers here and we need minimal services, like 500 MB disk space would probably be plenty, we don't care about any tracs or wikis or

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.