import axios from 'axios';
import { getToken } from '/@/utils/gfast';
import { ElMessage, ElLoading } from 'element-plus';
const baseUrl = import.meta.env.VITE_API_URL;
interface obj {
[key: string]: any
}
// 下载zip文件
export function downLoadFile(url: string, option: obj) {
let urlStr = baseUrl + url;
const loading = ElLoading.service({
lock: true,
text: '正在导出数据...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)',
});
axios({
method: option.type,
url: urlStr,
[option.type == 'get' ? 'params' : 'data']: option.data,
responseType: 'blob',
headers: { Authorization: 'Bearer ' + getToken() },
}).then((response) => {
loading.close();
exportExcleUtil(response)
}).catch(() => {
loading.close();
ElMessage({
message: '导出失败',
type: 'error',
});
});
}
// 解析blob内容下载,如果异常报错
const exportExcleUtil = (res: any) => {
if (res.data.type == 'application/json') {
const reader = new FileReader() as any;
reader.readAsText(res.data, 'utf-8');
reader.onload = function () {
const data = JSON.parse(reader.result);
if (data.code != 200) {
ElMessage({
message: data.message,
type: 'error',
});
}
}
} else {
// 解析请求头,获取文件名,如果拿不到响应头但是netWork有,就是后端没有把Access-Control-Expose-Headers中加入content-disposition的权限
const fileName = res.headers["content-disposition"].split("=")[1];
const blob = new Blob([res.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
const url = window.URL.createObjectURL(blob);
const aLink = document.createElement("a");
aLink.style.display = "none";
aLink.href = url;
aLink.setAttribute("download", decodeURI(fileName));
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
window.URL.revokeObjectURL(url);
}
}
前端(Vue、React)导出blob文件(excel、zip等)
最新推荐文章于 2024-06-06 10:02:08 发布
本文介绍了如何使用axios进行文件下载,包括处理不同类型的请求(如GET和POST),以及在下载Excel文件时的错误处理和文件名获取。着重展示了如何利用axios与后端API交互,并处理响应头中的文件名信息。
摘要由CSDN通过智能技术生成