How to convert base64-encoded URI data to a file *server side*?

1.2k Views Asked by At

I have a URI-data string that looks like this:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2w..... and so on

I need to save this to a jpg on the server, and using only Javascript. As a last resort, I could use the client to write this to a canvas and then read the image from there... but I'd really like to be able to do it on the server. For some reason, this is proving to be very complicated indeed.

Ideas??

1

There are 1 best solutions below

0
Marc On

Thanks for the tips, everyone! Here is the bit of code that finally did the trick:

    var fs = require("fs");
    var strippedPhotoUri = imageData.substring("data:image/jpeg;base64,".length);
    var buf = new Buffer(strippedPhotoUri, "base64");
    fs.writeFileSync(filename, buf, "base64", function(err) {
        if (err) {
            console.error("error: " + err);
        }
    });