XMLHttpRequest 返回错误编码的字符

2024-02-01

我使用 XMLHttpRequest 来读取 PDF 文档http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf

%PDF-1.3
%âãÏÓ
[...]

并将其内容打印到控制台:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log(xhr.responseText);
      console.log('âãÏÓ');
    }
};
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.send();

然而,控制台说

%PDF-1.3
%����
[...]
âãÏÓ

(最后一行来自参考文献console.log上面验证控制台实际上可以显示这些字符。) 显然,字符在某些时候被错误编码。出了什么问题以及如何解决这个问题?


XMLHttpRequest 的默认响应类型是text,但这里实际上是在处理二进制数据。埃里克·比德尔曼 http://www.html5rocks.com/en/tutorials/file/xhr2/描述如何使用它。

问题的解决方案是将数据读取为Blob,然后从 blob 中提取数据并将其插入hash.update(..., 'binary'):

var xhr = new XMLHttpRequest();
xhr.open('GET', details.url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
  if (this.status === 200) {
    var a = new FileReader();
    a.readAsBinaryString(this.response);
    a.onloadend = function() {
      var hash = crypto.createHash('sha1');
      hash.update(a.result, 'binary');
      console.log(hash.digest('hex'));
    };
  }
};
xhr.send(null);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XMLHttpRequest 返回错误编码的字符 的相关文章

随机推荐