情景1:如果存在CORS问题,先将图片转成base64 :(亲测有效)
downloadIamge(imgsrc, name) {//下载图片地址和自定义图片名称
let image = new Image();
// 解决跨域 Canvas 污染问题
image.setAttribute("crossOrigin", "anonymous");
image.onload = function() {
let canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
let a = document.createElement("a"); // 生成一个a元素
let event = new MouseEvent("click"); // 创建一个单击事件
a.download = name || "qrcode.jpg"; // 设置图片名称
a.href = url; // 将生成的URL设置为a.href属性
a.dispatchEvent(event); // 触发a的单击事件
};
image.src = imgsrc;
}
情景2:如果不存在CORS问题,可以借助Blob实现下载(构造xhr请求文件地址, 以Blob的形式接收Response):
function downloadWithBlob(url,name) {
fetch(url).then(res => res.blob().then(blob => {
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
var filename = name || 'qrcode.jpg';
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}));
}
情景3:如果有文件content:
function funDownload(content, filename) {
var eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
// 字符内容转变成blob地址
var blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};