本次所涉及到两种情况
1.文件在oss 上面 接口返回的是oss文件地址 进行下载并更改文件名称
2.接口返回的文件流 进行下载并更改文件名称
第一种情况:文件在oss上面
思路:
调用接口获取oss上文件地址
使用 new XMLHttpRequest 将相应格式改为 ‘blob’
进行改名与下载
代码块:
downloadFun() {
// 获取到的 文件地址
let url = 'https://sevenmin-app.oss-cn-beijing.aliyuncs.com/xlsx...'
this.getBlob(url).then(blob => {
this.goDownload(blob);
})
}
getBlob(url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (200 === xhr.status) {
resolve(xhr.response);
}
};
xhr.send();
});
}
goDownload(blob) {
const aEl = document.createElement('a');
aEl.href = window.URL.createObjectURL(blob);
aEl.download = this.getExcelName(); // 名字 例:xxx.xlsx
aEl.style.display = 'none';
document.body.appendChild(aEl);
aEl.click();
document.body.removeChild(aEl);
window.URL.revokeObjectURL(aEl.href);
}
第二种情况:接口返回的文件流
思路:
接口请求时,请求响应格式 设置为 responseType: 'blob'
blob转file 获取url
设置改名与下载
代码块:
// 请求接口
export function exportPool (parameter) {
return axios({
url: api.exportPoolApi,
method: 'post',
data: parameter,
responseType: 'blob' // !!! 设置这里
})
}
// 调用接口
exportPool(data).then((res) => {
this.downloadBlob(res)
}).catch(err => {
this.$message.error('接口异常')
})
downloadBlob(data) {
// 下载文件
if (!data) {
return
}
const url = window.URL.createObjectURL(new Blob([data])) // 根据实际返回的数据格式进行调整
const aEl = document.createElement('a')
aEl.style.display = 'none'
aEl.href = url
aEl.setAttribute('download', 'EXCEL.xls') // 设置的名称与后缀名
document.body.appendChild(aEl)
aEl.click()
document.body.removeChild(aEl);
window.URL.revokeObjectURL(aEl.href);
}