new Promise((resolve) => {
const xhr = new XMLHttpRequest();
xhr.open(
'GET',
url,
true
);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status !== 200) {
ElMessage.error('下载失败,请重试');
return;
}
let a = document.createElement('a');
a.download = row.name;
a.style.display = 'none';
a.href = window.URL.createObjectURL(xhr.response);
document.body.appendChild(a);
a.click();
a.remove();
};
xhr.send();
});
查到的各种文档都说用a.download就能直接下载,但是实际使用发现不行,如果后端支持给链接加上?response-content-type=application/octet-stream'其实是最简单的,前端就直接下载了。但是如果后端不改的话就要用到这个方法,xhr打开路径之后用createObjectURL转blob再下载即可。