我在远程服务器上有一个文件,它是二进制的,我知道如何处理它的位。但是我无法使用 Javascript 下载并将其呈现为二进制字符串以供浏览器使用。从我读到的内容来看,这是我得到的:
function loadFile() {
$.get('binaryfile.ext', function(data) {
new FileReader().readAsBinaryString(data);
});
}
但是我收到此错误:
Uncaught TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': The argument is not a Blob.
文件正在正确下载,如果我document.write(data)
它会按预期打印文件的内容。
我在网络上找不到有效的操作方法或示例,我正在搜索大约 16 个小时。
对此不是百分百确定,但我相信你不能用jQuery的ajax方法获取二进制数据。现在有了html5
也许事情可能会有所改变。无论如何,这里有一个黑客方法,你可以做到这一点。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'binaryfile.ext', true);
// Hack to pass bytes through unprocessed.
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
var binStr = this.responseText;
for (var i = 0, len = binStr.length; i < len; ++i) {
var c = binStr.charCodeAt(i);
//String.fromCharCode(c & 0xff);
var byte = c & 0xff; // byte at offset i
}
}
};
xhr.send();
您可以在此处找到更多信息:http://www.html5rocks.com/en/tutorials/file/xhr2/