2011-08-31 108 views
6

我试图使用XMLHttpRequest检索Javascript中图像的数据。使用XMLHttpRequest下载二进制数据,不需要overrideMimeType

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,然而任何高值中的字节返回作为0xfffd0xfffd & 0xff0xfd)。

问题如this one提供使用overrideMimeType()函数的解决方案,但是在我使用的平台(Qt/QML)上不支持这种解决方案。

如何正确下载数据?

+1

您是否尝试过使用base64编码? – cvsguimaraes

+0

我会如何尝试? – funkybro

+0

似乎这是不可能的;我将使用Qt/C++代替原生本地下载。 – funkybro

回答

5

Google I/O 2011: HTML5 Showcase for Web Developers: The Wow and the 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(); 
+3

不适合我,'xhr.response'是未定义的。 – funkybro

+0

我很乐意为您提供免费的啤酒发布链接 –

+0

备注:未来的读者:如果您使用arraybuffer作为responseType,chrome将不会为onprogress事件设置xhr.response属性。所以这个方法在Chrome浏览器下渐进式下载/上传是没用的。 – yms

0

我不会使用Qt熟悉,但我发现这个在他们documentation

string Qt::btoa (data) 
Binary to ASCII - this function returns a base64 encoding of data. 

所以,如果你的形象是一个PNG,你可以尝试:

resp = "data:image/png;base64," + btoa(resp); 
document.write("<img src=\""+resp+"\">"); 
+0

我不知道如果我不能通过字符串访问正确的字节值将如何工作。 – funkybro

+0

从0开始!布局引擎总是忽略与重新映射图像无关的内容。 – cvsguimaraes

相关问题