1,一般下载文件后端给个URL直接调用window.open(url)或者window.location.href=url即可。
2,特殊情况下后台要返回字节流,前端用字节流生成文件
1)首先给请求设置 responseType: 'blob'
2)request(api).then((res) => {
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', file.fileName)
document.body.appendChild(link)
link.click()
link.remove()
})
然后即可下载。
3)需要注意的是blob只兼容IE10及以上版本,使用时应注意。
3,window.open 会打开新的标签,用户体验不是很好,可以使用下面的方法。
const iframe = document.createElement('iframe');
iframe.style.display = 'none'; // 防止影响页面
iframe.style.height = 0; // 防止影响页面
iframe.src = row.report_url;
document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求
// 5分钟之后删除(onload方法对于下载链接不起作用,就先抠脚一下吧)
setTimeout(() => {
iframe.remove();
}, 5 * 60 * 1000);
}, 1000)
其实a标签+download属性,也可以实现单个文件下载,但是下载多个文件时,只会下载一个,其他的会被cancel掉,具体原因不清楚
网友评论