Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading binary data using XMLHttpRequest, without overrideMimeType

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?

like image 714
funkybro Avatar asked Aug 31 '11 10:08

funkybro


1 Answers

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();
like image 197
user278064 Avatar answered Oct 21 '22 16:10

user278064