js下载绝对路径的图片

 

function down(){
    var imgUrl = document.getElementById("img").src;
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();   //用于在后台与服务器交换数据
    xmlhttp.open("GET", imgUrl, true);   //语法  open(method,url,async)
    xmlhttp.responseType = "blob"; // 请求返回的数据类型
    xmlhttp.onload = function() { //处理返回的数据
        if (this.status == 200) {
            var blob = this.response;
            var a = document.createElement('a');
            a.href = window.URL.createObjectURL(blob); //图片地址
            a.download = 'down.jpg'; //下载时 图片命名    如果没有默认是下载的图片的路径
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    };
    xmlhttp.send();   //用于发送http请求
}

 

posted @ 2020-12-17 10:36  木板  阅读(440)  评论(0)    收藏  举报