0

I thought these two pieces of code (they work in Chrome and Firefox) were supposed to do the same thing, but they behave in different ways. They send the binary contents of a file via an XmlHttpRequest object.

Direct XHR send:

xhr.send(file);

Read file and send contents via XHR:

var reader = new FileReader();
reader.onload = function(event) {
    xhr.send(event.target.result);
};
reader.readAsBinaryString(file);

File bytes sent do not match between requests (in the second one, the file is larger than in the first one, and the file gets corrupted).

I need to make the second option work.

Any ideas?

Ben
  • 54,723
  • 49
  • 178
  • 224
German Latorre
  • 10,058
  • 14
  • 48
  • 59

1 Answers1

1

I ran into a similar problem - Corruption with FileReader into FormData

The reader's result is a string; you need to convert it into an array buffer:

var result = e.target.result;
var l = result.length
var ui8a = new Uint8Array(l)
for (var i = 0; i < l; i++)
  ui8a[i] = result.charCodeAt(i);
var bb = new (window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder)()
bb.append(ui8a.buffer)
xhr.send(bb.getBlob())
Community
  • 1
  • 1
aeosynth
  • 20,750
  • 2
  • 21
  • 18
  • It works in firefox and webkit. opera doesn't have BlobBuilder or typed arrays. [BlobBuilder.js](https://github.com/eligrey/BlobBuilder.js) gets you BlobBuilder, I'm trying to figure out how to deal w/ lack of typed arrays. – aeosynth Aug 29 '11 at 22:25