a标签加download属性,有同源限制,把图片转换下再下载
利用canvas的toDataUri方法
// 已有远程且非同源图片链接originUrl
saveImg() {
const img = new Image();
img.src = originUrl;
img.setAttribute('crossOrigin', 'Anonymous');
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = 350;
canvas.height = 350;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, 350, 350);
// 或使用toBlob转为blob对象
const imgDataUri = ctx.toDataURL(); // <图片属性><图片质量>('image/png', 0.92)
// 利用a标签下载
const a = document.createElement('a');
a.download = '';
a.href = imgDataUri;
document.body.appendChild(a);
a.click();
a.remove();
}
}
使用window.URL.createObjectURL转换文件然后下载
const src = '文件路径';
// 直接请求此文件路径并设置restype为blob格式
const xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.responseType = 'blob';
xhr.onreadystatechange = async function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 304) {
const blob = xhr.response;
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '';
a.click();
a.remove();
}
}
};
xhr.send();