同源
const link = document.createElement('a');
link.setAttribute('download', file.name);
link.href = file.url;
link.click();
不同源
//方法一:
const xhr = new XMLHttpRequest();
xhr.open('GET', file.href, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
// 获取文件blob数据并保存
const urlObject = window.URL;
const export_blob = new Blob([xhr.response]);
const link = document.createElement('a');
link.href = urlObject.createObjectURL(export_blob);
link.download = file.name;
link.click();
}
};
xhr.send();
//方法二:
fetch(file.url).then(res => {
res.blob().then(data => {
const link = document.createElement('a');
const _url = window.URL.createObjectURL(data);
link.href = _url;
link.download = file.name;
link.click();
window.URL.revokeObjectURL(_url);
});
});