kateray
kateray

Reputation: 2246

Send Image File via XHR on Chrome

I'm using HTML5 drag&drop to get images from a user's computer and want to upload them to my Rails server (using Carrierwave on that end). I don't know exactly what I'm doing here, but cobbled together this code from these instructions http://code.google.com/p/html5uploader/wiki/HTML5Uploader

This returns a 500 error - can anyone take a look and help me out with what I'm doing wrong?

var files = e.dataTransfer.files;
if (files.length){
  for (var i = 0; i<files.length; i++) {
    var file = files[i];
    var reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = function() {
      var bin = reader.result;
      var xhr = new XMLHttpRequest();
      var boundary = 'xxxxxxxxx';
      xhr.open('POST', '/images?up=true&base64=true', true);
      xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
      xhr.setRequestHeader('UP-FILENAME', file.name);
      xhr.setRequestHeader('UP-SIZE', file.size);
      xhr.setRequestHeader('UP-TYPE', file.type);
      xhr.send(window.btoa(bin));
    };
  };
};

Upvotes: 2

Views: 1941

Answers (1)

ebidel
ebidel

Reputation: 24109

There are a couple of things that could be the culprit. You're reading the file as a binary string, then creating a multipart request, then sending a base64 encoded value.

There's no need to read the file or mess with base64 encoding. Instead, just construct a FormData object, append the file, and send that directly using xhr.send(formData). See my response here.

Upvotes: 3

Related Questions