9

IE10似乎不支持JavaScript 对象的方法readAsBinaryString 。按照HTML5 Rocks 文章FileReader中的建议,我尝试了以下方法:

String.fromCharCode.apply(null, new Uint16Array(buffer));

但是,这会导致Out of stack space错误。

4

4 回答 4

20

I found the answer here:

var binary = "";
var bytes = new Uint8Array(buffer);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
  binary += String.fromCharCode(bytes[i]);
}
于 2013-09-03T01:32:32.537 回答
3

从大卫琼斯的回答中,我写了这个方法。try/catch 处理 IE10/11 中的 readAsBinaryString 异常,并称自己为“IE 模式”:

function readBinaryStringFromBlob(blob, callback, ie) {
    var reader = new FileReader();
    if(!ie) {
        reader.addEventListener("loadend", function () {
            callback(reader.result);
        });
        try {
            reader.readAsBinaryString(blob);
        } catch (err) {
            readBinaryStringFromBlob(blob, callback, true);
        }
    } else {
        reader.addEventListener("loadend", function () {
            var binary = "";
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            callback(binary);
        });
        reader.readAsArrayBuffer(blob);
    }
}
于 2016-01-12T11:31:12.200 回答
2

如果你想要一些更简洁和 ES2015-ier 的东西,那么这可能就是你所追求的:

  const reader = new FileReader();
  reader.onerror = e => alert("File cannot be opened");

  if (reader.readAsBinaryString) {
     reader.onload = e => alert(e.target.result));
     reader.readAsBinaryString(file);
  }
  else {
     // Catering for IE 10/11
     reader.onload = e => {
        const bytes = new Uint8Array(e.target.result);
        const binary = bytes.reduce((acc, byte) => acc + String.fromCharCode(byte), "");
        alert(binary);
     };
     reader.readAsArrayBuffer(file);
  }
于 2016-09-27T12:47:40.433 回答
0

试试我的代码:

    function readAsBinaryString(blob, callback) {
        var reader = new FileReader();

        var binStringCallback = function (e) {
            callback(e.target.result);
        };

        var arrBufferCallback = function (e) {
            var binary = "";
            var bytes = new Uint8Array(e.target.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            callback(binary);
        };

        reader.onerror = reader.onabort = function () {
            callback(null)
        };

        if (typeof reader.readAsBinaryString != "undefined") {
            reader.onload = binStringCallback;
            reader.readAsBinaryString(blob);
        } else {
            reader.onload = arrBufferCallback;
            reader.readAsArrayBuffer(blob);
        }
    }
于 2016-01-19T11:21:48.917 回答