6

I have the following code to upload to my Node.js/Express.js backend.

var reader = new FileReader();
reader.readAsDataURL(file);

reader.onload = function (e) {
  var result = http.post('/files', e.target.result);
  result.success(function () { 
    alert('done'):
  });
}

My route looks like:

app.post('/files', function (req, res) {
  var cws = fs.createWriteStream(__dirname + '/media/file');
  req.pipe(cws);
  res.send('success');
});

When I open /media/file with an image app I get a warning that it cannot read it. When I open the image file with a text-editor I see the base64 encoded string inside. Do I need to convert the string first before writing it to desk?

3
  • Which FileReader implementation are you using?
    – matthias
    Oct 25, 2012 at 14:02
  • Not sure which one I am using Chrome 18. After some digging it seems the DataURL is prepended with some meta data I need to remove.
    – Pickels
    Oct 25, 2012 at 14:18
  • Yep, that's what I figured out as well (facing similar issue on my own). Probably a splitting followed by a base64-decode solves this issue.
    – matthias
    Oct 25, 2012 at 14:21

1 Answer 1

8

The problem was that a DataURL is prepended by meta data. You first need to remove that part before you create a base64 buffer.

var data_url = req.body.file;
var matches = data_url.match(/^data:.+\/(.+);base64,(.*)$/);
var ext = matches[1];
var base64_data = matches[2];
var buffer = new Buffer(base64_data, 'base64');

fs.writeFile(__dirname + '/media/file', buffer, function (err) {
  res.send('success');
});

Got most code from this question.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.