为什么XMLHttpRequest响应的长度与请求的文件大小不同?

时间:2015-03-17 14:11:35

标签: javascript xmlhttprequest response filesize

如果文件的实际大小为6327字节(响应头中的内容长度为6327),

那么为什么XMLHttpRequest响应的长度(下面代码中的xhr.response.length的值)不同:

Chrome中的6085(版本41)和Firefox(版本36)中的5961?

//run this code somewhere on google.com to avoid access error
var xhr = new XMLHttpRequest();
xhr.open('GET','https://www.google.com/images/errors/robot.png',true);
xhr.onreadystatechange=function(e){
    if(xhr.readyState==4&&xhr.status==200){
        console.log(xhr.response.length);
    }
};
xhr.send();

命令

xhr.setRequestHeader('Content-Type','image/png');

或命令

xhr.setRequestHeader('Content-Type','application/zip');

无济于事。

1 个答案:

答案 0 :(得分:2)

必须覆盖MIME类型:

var xhr = new XMLHttpRequest();
xhr.open('GET','https://www.google.com/images/errors/robot.png',true);
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.onreadystatechange=function(e){
    if(xhr.readyState==4&&xhr.status==200){
        console.log(xhr.response.length);
    }
};
xhr.send();

实际上,它不是问题的最佳答案,但工作正常(xhr.response.length的值等于文件大小)。

相关问题