js 下载图片到本地

1.下载同源图片问题 (使用a标签下载)

var img_src = obj.getAttribute('data-src')

var a = document.createElement('a');

a.href = img_src; //图片地址

a.download = 'test'; // 图片名字

document.body.appendChild(a);

a.click();

document.body.removeChild(a);

2.下载不同源图片 xmlhttp 获取图片blob格式 再使用window.URL.revokeObjectURL(blob)创建可访问的链家

将链家赋值给a.href 可完成下载

var url = obj.getAttribute('data-src')

var xmlhttp;

xmlhttp = new XMLHttpRequest();

xmlhttp.open("GET", url, true);

xmlhttp.responseType = "blob"; // 请求返回的数据类型

xmlhttp.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);

document.body.appendChild(img);

var a = document.createElement('a'); // 下载图片

a.href = window.URL.createObjectURL(blob); //图片地址

a.download = 'test.jpg'; // 图片名字

document.body.appendChild(a);

a.click();

document.body.removeChild(a);

}

}

xmlhttp.send();


github 例子  https://github.com/a1044187112/download-img 

注意:1.chrome  不能同时下载多个文件 ,浏览器会拦截

           2. 图片所在服务器需要允许跨域访问的才可以,没有设置的在xmlhttp获取数据时报错

你可能感兴趣的:(js 下载图片到本地)