一般都是后端传一个blob的形式给前端,前端将其处理为url,在进行点击处理。
有一种最简单的方式就是,但是这种会打开另外一个标签栏,不符合开发需求
window.open(url)
所以我们可以先将后端传的url转为blob形式
let fileName = url.slice(url.lastIndexOf('/') + 1); // 这里是通过从后端获取到的 url 地址中截出来原本的文件名
fetch(url).then((res) => res.blob()).then((blob) => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
// 下载文件的名称及文件类型后缀
link.download = fileName;
document.body.appendChild(link);
link.click();
//在资源下载完成后 清除 占用的缓存资源
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
});