一般都是通過創建A標簽,使用download屬性進行下載,但是,如果遇到跨域的圖片,就會直接打開圖片,無法下載,這時,通過下面的方式即可:
方法一:
function downLoadImage(imgsrc,name){
var shijc = new Date().getTime();
imgsrc = imgsrc + "?t=" + shijc;
var image = new Image();
// 解決跨域 Canvas 污染問題
image.setAttribute("crossOrigin", "anonymous");
image.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
var url = canvas.toDataURL("image/png",0.7); //得到圖片的base64編碼數據
var a = document.createElement("a"); // 生成一個a元素
var event = new MouseEvent("click"); // 創建一個單擊事件
a.download = name?name+'.png':"photo.png"; // 設置圖片名稱
a.href = url; // 將生成的URL設置為a.href屬性
a.dispatchEvent(event); // 觸發a的單擊事件
};
image.src = imgsrc;
}
方法二:
function downloadnewimg(src, name) {
src = src + "?t=" + new Date().getTime();
fetch(src).then((response) => {
response.blob().then((myBlob) => {
const href = URL.createObjectURL(myBlob);
let a = document.createElement("a");
a.href = href;
a.download = name;
a.click();
});
});
}
-------
僅僅前端這樣還不夠,還需要圖片服務器進行以下設置:
在寶塔的設置》配置文件里,或者偽靜態設置里,加入以下代碼:
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";