将图片地址转为blob格式的例子

时间:2024-02-24 21:53:03

HTML代码:

<div id="forAppend" class="demo"></div>

Javascript代码:

<script>
var eleAppend = document.getElementById("forAppend");
window.URL = window.URL || window.webkitURL;
if (typeof history.pushState == "function") {
    var xhr = new XMLHttpRequest();    
    xhr.open("get", "此处填写您的图片地址", true);
    xhr.responseType = "blob";
    xhr.onload = function() {
        if (this.status == 200) {
            var blob = this.response;
            var img = document.createElement("img");
            img.onload = function(e) {
              window.URL.revokeObjectURL(img.src); // 清除释放
            };
            img.src = window.URL.createObjectURL(blob);
            eleAppend.appendChild(img);    
        }
    }
    xhr.send();
} else {
    eleAppend.innerHTML = \'<p style="color:#cd0000;">请更换浏览器重试~</p>\';    
}
</script>

请务必在环境下运行

(来源:http://www.zhangxinxu.com/study/201310/blob-get-image-show.html   类似知识:http://blog.csdn.net/oscar999/article/details/36373183)