您還可以直接從 XMLHttpRequest 獲取 BLOB 對象。將responseType 設(shè)置為blob 就可以了。這是我的代碼:
var xhr = new XMLHttpRequest(); xhr.open("GET", "http://localhost/image.jpg"); xhr.responseType = "blob"; xhr.onload = response; xhr.send();
響應(yīng)函數(shù)如下所示:
function response(e) { var urlCreator = window.URL || window.webkitURL; var imageUrl = urlCreator.createObjectURL(this.response); document.querySelector("#image").src = imageUrl; }
我們只需在 HTML 中創(chuàng)建一個空圖像元素即可:
<img id="image"/>
問題是我有十六進(jìn)制數(shù)據(jù),需要在進(jìn)行 Base64 編碼之前轉(zhuǎn)換為二進(jìn)制。
在 PHP 中:
base64_encode(pack("H*", $subvalue))