Skip to content

Instantly share code, notes, and snippets.

@mawenbao
Last active October 12, 2016 05:58
Show Gist options
  • Save mawenbao/22fd263fe1a18dfe941f313f84fd8bd8 to your computer and use it in GitHub Desktop.
Save mawenbao/22fd263fe1a18dfe941f313f84fd8bd8 to your computer and use it in GitHub Desktop.
Fetch remote image with xhr
var url = 'https://static.mawenbao.com/images/cartoon/%E7%BB%88%E6%9C%AB%E7%9A%84%E4%BC%8A%E6%B3%BD%E5%A1%94.jpg';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
if (xhr.overrideMimeType) xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.setRequestHeader("Content-Type", "application/octet-stream");
var txt = '';
function handle() {
if (this.readyState != null && (this.readyState < 3 || this.status != 200)) {
return
}
txt += this.responseText;
}
xhr.onreadystatechange = handle;
xhr.send(null);
var binArr = new Uint8Array(txt.length);
for (var i = 0; i < txt.length; i++) {
binArr[i] = txt.charCodeAt(i);
}
var img = document.createElement('img');
img.src = window.URL.createObjectURL(new Blob([binArr]));
document.body.appendChild(img);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment