js 下載圖片到本地

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ù)時報錯

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容