使用 window.location.href 和 window.open 后都是打开图片,原因是,当浏览器发现是浏览器支持的文件类型,例如 jpg、png、svg 等,默认是浏览器打开。
解决
fetch + createObjectURL
fetch 转换为 blob 对象
createObjectURL() 静态方法创建一个用于表示参数中给出的对象的 URL 的字符串
function downloadImg(url) {
fetch(url, {
headers: new Headers({
Origin: location.origin,
}),
mode: 'cors',
})
.then((res) => {
if (res.status == 200) {
// 生成 blob 对象
return res.blob();
}
throw new Error(`status: ${res.status}.`);
})
.then((blob) => {
download(blob, 'image');
});
}
function download(blob: Blob, filename?: string) {
const a: any = document.createElement('a');
a.download = filename;
const blobUrl = URL.createObjectURL(blob);
a.href = blobUrl;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(blobUrl);
}