简单来说下载二进制文件流就是将二进制文件流存在 Blob 对象中,再将其转为 url 对象,最后通过 a 标签下载。
//封装下载
export function downLoadFetch(url, params = {}, config={}) {
//取消
const downSource = axios.CancelToken.source();
document.getElementById('downAnimate').style.display = 'block';
document.getElementById('cancelBtn').addEventListener('click', function(){
downSource.cancel("用户取消下载");
document.getElementById('downAnimate').style.display = 'none';
}, false);
//参数
config.params = params;
//超时时间
config.timeout = config.timeout ? config.timeout : defaultDownConfig.timeout;
//类型
config.responseType = defaultDownConfig.responseType;
//取消下载
config.cancelToken = downSource.token;
return instance.get(url, config).then(response=>{
const content = response.data;
const url = window.URL.createObjectURL(new Blob([content]));
//创建 a 标签
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
//文件名 Content-Disposition: attachment; filename=download.txt
const filename = response.headers['content-disposition'].split(";")[1].split("=")[1];
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
return {
status: 200,
success: true
}
})
}
vue写法
下载excel
// 下载学生列表
down_list(){
let data = {}
let that = this
schoolClass_exportStudentData(data).then(res =>{
if (res.data) {
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
const fileName = '这就是列表名字' + '.' + 'xls'
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} else {
that.$message({
message: res.data.msg,
type: 'error'
})
}
})
},
// 下载
down_list_btn(){
this.down_list()
},
// 封装请求的地方需要这么写:
export function schoolClass_exportStudentData(data){
return request({
url:"/signup/exportStudentData",
method:"post",
data,
responseType: 'blob'
})
}
下载zip
// 下载
handleDown(row) {
downloadShare(row.id).then((response) => {
this.downloadFile(response, row);
});
},
downloadFile(data, row) {
let blob = new Blob([data], { type: "application/zip" });
let url = window.URL.createObjectURL(blob);
const link = document.createElement("a"); // 创建a标签
link.href = url;
link.download = row.dataSetVersion + '-' + formalDateTime(new Date().getTime() / 1000, 5); // 重命名文件
link.click();
URL.revokeObjectURL(url); // 释放内存
},
// 封装请求的地方需要这么写:
// 获取 下载共享
export function downloadShare(id) {
return request({
url: '/ai/share/download/' + id,
method: 'get',
responseType: 'blob',
headers: {
'Conntent-Type': 'application/json; application/octet-stream;'
}
})
}