Downloading binary data using XMLHttpRequest, without overrideMimeType

别来无恙 提交于 2019-12-28 06:35:41

问题


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();

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

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

How can I download the data correctly?


回答1:


Google I/O 2011: HTML5 Showcase for Web Developers: The Wow and the How

Fetch binary file: new hotness

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();



回答2:


I'm not familiarized with Qt but i found this in their documentation

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

So, if your image is a png you can try:

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


来源:https://stackoverflow.com/questions/7255719/downloading-binary-data-using-xmlhttprequest-without-overridemimetype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!