使用 XMLHttpRequest 下载二进制数据,无需 overrideMimeType [英] Downloading binary data using XMLHttpRequest, without overrideMimeType

查看:30
本文介绍了使用 XMLHttpRequest 下载二进制数据,无需 overrideMimeType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 XMLHttpRequest 在 Javascript 中检索图像数据.

I am trying to retrieve the data of an image in Javascript using XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.celticfc.net/images/doc/celticcrest.png");
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        var resp = xhr.responseText;
        console.log(resp.charCodeAt(0) & 0xff);
    }
};
xhr.send();

此数据的第一个字节应为 0x89,但是任何高值字节返回为 0xfffd(0xfffd & 0xff 为 <代码>0xfd).

The first byte of this data should be 0x89, however any high-value bytes return as 0xfffd (0xfffd & 0xff being 0xfd).

诸如这个问题 使用 overrideMimeType() 函数提供解决方案,但是我使用的平台 (Qt/QML) 不支持此功能.

Questions such as this one offer solutions using the overrideMimeType() function, however this is not supported on the platform I am using (Qt/QML).

如何正确下载数据?

推荐答案

Google I/O 2011:面向 Web 开发人员的 HTML5 展示:The Wow 和 How

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.celticfc.net/images/doc/celticcrest.png', true);

xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
   if (this.status == 200) {
       var uInt8Array = new Uint8Array(this.response); // Note:not xhr.responseText

       for (var i = 0, len = uInt8Array.length; i < len; ++i) {
           uInt8Array[i] = this.response[i];
       }

       var byte3 = uInt8Array[4]; // byte at offset 4
   }
}

xhr.send();

这篇关于使用 XMLHttpRequest 下载二进制数据,无需 overrideMimeType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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