开发者

HTML5 File API XmlHttpRequest send(file) different than sending readAsBinaryString() result

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 th开发者_JAVA百科e 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?


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())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜