在你封装的请求方法里面加上如上属性
// 导出
export function daochu(query) {
return axios({
url: `你的地址`,
method: "GET",
// 加上这个属性
responseType: "arraybuffer",
});
}
页面代码如下
// 导出
btn_daochu() {
console.log(new Date().getTime());
if (this.art && this.art.length > 0) {
//导出excel
this.$confirm("此操作将导出所选分包队伍, 是否继续?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
this.loading_dr = true
this.is_daochu = true
const res = await daochu(this.art)
console.log(res);
if (res.data) {
this.loading_dr = false
this.is_daochu = false
}
// res.data为后端返回的二进制文件流
let blob = new Blob([res.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8",
});
let timestampToTimes = this.timestampToTime(new Date().getTime())
let fileName = "分包队伍名单" + timestampToTimes;
let a = document.createElement("a");
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.style.display = "none";
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
})
} else {
this.$message.error('请选择要导出的数据')
}
},
// 时间戳转换为日期格式
timestampToTime(timestamp) {
var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = date.getDate() + ' ';
var h = date.getHours() + ':';
var m = date.getMinutes() + ':';
var s = date.getSeconds();
return Y + M + D + h + m + s;
}
注:如果不加时间戳纯粹的是死的文件名,多次导出会出问题