export const 导出函数 = async () => {
const res = await axios({ url: `链接地址`, method: "post", headers: { "Content-Type": "application/json" }, data: { }, responseType: "blob" });
return res.data;
};
把导出的数据传递到下边的函数中,即可导出下载excel文件
download (data) {
// data是文件流
if (!data) {
return;
}
let blob = new Blob([data], {
type: 'application/vnd.ms-excel;charset=utf-8', // 文件类型
});
let url = window.URL.createObjectURL(blob);
let fileName = "下载文件"; // 文件名称
if ("download" in document.createElement("a")) {
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.style.display = "none";
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}
}
以上是导出的功能;接下来写导入的功能
export const 导入函数 = async (file) => {
// 构建FormData对象,通过该对象存储要上传的文件
const formData = new FormData();
const renameFile = new File([file], file.name.replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, "_"), { type: file.type });
// 遍历当前临时文件List,将上传文件添加到FormData对象中
formData.append("file", renameFile);
// 调用后端接口,发送请求
const res = await axios.post(`接口地址`, formData, {
// 因为我们上传了图片,因此需要单独执行请求头的Content-Type
headers: {
// 表示上传的是文件,而不是普通的表单数据
"Content-Type": "multipart/form-data"
}
});
if (res.data === "文件上传失败") {
// ElMessage.error(res.data);
return "";
}
return res.data;
};
点击导入按钮后可以打开导入,以下是代码
<input id="fileUpload" type="file" accept="image/pdf" style="opacity: 0; cursor: pointer;"
@change="导入函数($event)"
/>
调用导入函数
导入函数() {let fileObj = e.currentTarget.files[0]; } 把fileObj 传递到导入的接口即可