XMLHttpRequest返回错误编码的字符 [英] XMLHttpRequest returns wrongly encoded characters

查看:115
本文介绍了XMLHttpRequest返回错误编码的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use XMLHttpRequest to read the PDF document http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf

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

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

and print its content out to console:

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 ,以验证控制台是否可以实际显示这些字符。 )
显然,字符在某些时候被错误编码。出了什么问题以及如何解决这个问题?

(The last line is from the reference console.log above to verify that the console can actually display those characters.) Apparently, the characters are wrongly encoded at some point. What's going wrong and how to fix this?

推荐答案

XMLHttpRequest的默认响应类型是 text ,但这里实际上是处理二进制数据。 Eric Bidelman 介绍了如何使用它。

XMLHttpRequest's default response type is text, but here one is actually dealing with binary data. Eric Bidelman describes how to work with it.

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

The solution to the problem is to read the data as a Blob, then to extract the data from the blob and plug it into 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);

这篇关于XMLHttpRequest返回错误编码的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆