前言
vue实现导出表格,后端返回的是二进制流文件格式,前端如何处理然后导出表格。
此功能需要先导入表格,导入完成后会返回二进制流文件格式的表格去导出。
首先还是借助iview 的Upload 上传组件,以下是组件的一些属性设置:
format:支持的文件类型,on-format-error:文件格式验证失败时的钩子,action:上传的地址,before-upload:上传文件之前的钩子。
<Upload
:format="['xls', 'xlsx', 'csv']"
:on-format-error="handleGaodeFormatError"
:show-upload-list="false"
:action="''"
:before-upload="handleUpload"
>
<Button type="success" size="default" style="margin: 10px" :loading="uploadBtnLoading"
>导出</Button
>
</Upload>
在选择文件时验证,只能选择表格类型。
// 文件格式验证失败时的钩子
handleGaodeFormatError(file) {
this.$Message.warning("选择文件格式错误,请选择Excel文件!");
},
借助上传文件之前的钩子,获取到上传的文件数据,设置return false,阻止自动上传。
handleUpload(file) {
this.uploadBtnLoading = true;
this.handleUploadModel(file);
//阻止自动上传
return false;
},
在上传文件时,需要设置服务端返回的数据类型为responseType: “blob”。
New FileReader() 的使用
FileReader :读取文件内容
onloadend:文件读取完毕之后,不管成功还是失败触发
readAsText(): 读取文本文件,(可以使用Txt打开的文件)
// 导出失败原因
handleUploadModel(file) {
let fileFormData = new FormData();
fileFormData.append("file", file);
const instance = axios.create({
withCredentials: true,
});
instance({
url: this.uploadGaodeExcel, // 上传地址
method: "POST",
data: fileFormData,
responseType: "blob",
}).then((res) => {
// console.log(res,"res")
const resData = res.data
this.uploadBtnLoading = false;
if (resData.type === 'application/json') {
// 说明是普通对象数据,读取信息
const fileReader = new FileReader()
fileReader.onloadend = () => {
const jsonData = JSON.parse(fileReader.result)
// 后台信息
// console.log(jsonData)
if(jsonData.code != 200){
return this.$Message.error(jsonData.message);
}
}
fileReader.readAsText(resData)
} else {
// 下载文件
const blob = new Blob([resData], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const href = URL.createObjectURL(blob); // 创建新的URL表示指定的blob对象
const a = document.createElement("a"); // 创建a标签
a.style.display = "none";
a.href = href; // 指定下载链接
//设置指定元素上的某个属性值。如果属性已经存在,则更新该值
a.setAttribute("download", "失败原因.xlsx");
a.click(); // 触发下载
URL.revokeObjectURL(a.href); // 释放URL对象
}
})
},
这是上传完成后后端返回的二进制流文件数据。
这是设置了返回的数据类型responseType后拿到的数据,下载文件时的type应与此处的type类型保持一致。
这样就可以下载成功啦!!!