2011-08-31 82 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

相關問題