1.下載同源圖片問題 (使用a標(biāo)簽下載)
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)創(chuàng)建可訪問的鏈家
將鏈家賦值給a.href 可完成下載
var url = obj.getAttribute('data-src')
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.responseType = "blob"; // 請求返回的數(shù)據(jù)類型
xmlhttp.onload = function() {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement("img"); // 預(yù)覽圖片
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. 圖片所在服務(wù)器需要允許跨域訪問的才可以,沒有設(shè)置的在xmlhttp獲取數(shù)據(jù)時報錯