IE10中似乎不支持readAsBinaryString,即JavaScript FileReader
对象的方法。我按照this HTML5 Rocks article中的建议尝试了以下内容:
String.fromCharCode.apply(null, new Uint16Array(buffer));
但是,这会导致Out of stack space
错误。
答案 0 :(得分:19)
我找到了答案here:
var binary = "";
var bytes = new Uint8Array(buffer);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
答案 1 :(得分:2)
根据David Jones的回答,我写了这个方法。 try / catch处理IE10 / 11中的readAsBinaryString异常并将其自身称为&#34; IE模式&#34;:
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);
}
}
答案 2 :(得分: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);
}
答案 3 :(得分: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);
}
}