总结下载文件的几种方式,文件都是通过接口获取的,前端通过调用接口将接口返回的文件下载。
1、window.open
适用于get请求,体验不是很好,会弹出一个新的页签
window.open(url)
2、window.location.href
适用于get请求,体验不是很好,会覆盖单前页签的页面
window.location.href = url;
3、a标签
适用于get请求,体验比较好,用户对下载页面的变化无感知
/**
* 通过 a标签下载文件
* @param url 文件的链接
*/
export function download(url) {
const link = document.createElement('a');
document.body.appendChild(link);
link.href = url;
link.download = 'download';
link.click();
setTimeout(() => {
if (link.remove) {
link.remove();
} else if (link.removeNode) {
link.removeNode();
}
}, 20000);
}
4、iframe
适用于get请求,体验比较好,用户对下载页面的变化无感知
/**
* 通过 iframe 下载文件
* @param url 文件的链接
*/
export function download(url) {
const $iframe = document.createElement('iframe');
$iframe.style.height = '0px';
$iframe.style.width = '0px';
document.body.appendChild($iframe);
$iframe.setAttribute('src', url);
setTimeout(() => {
if ($iframe.remove) {
$iframe.remove();
} else if ($iframe.removeNode) {
$iframe.removeNode();
}
}, 20000);
}
5、blob
适用于post请求,需传递大量参数获取的时候,从用户触发到文件下载有较大时延,需要加loading告知用户
注意: responseType在axios的config里,不在header里
/**
* post请求导出列表
* @param url 访问路径
* @param data 请求参数,数组
* @param fileName 导出文件名
* @param formatStr 日期格式化
*/
export function download(url, data, fileName, formatStr) {
axios({
method: 'post',
url,
data,
responseType: 'blob'
}).then(res => {
const link = document.createElement('a');
let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
link.setAttribute('download', fileName + new Date().format(formatStr) + '.xls');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
下载成预览返回头配置、默认文件名
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=文件名.后缀