<el-button
link
type="primary"
size="large"
@click="downProfile(row.resId)"
>下载</el-button>
const downProfile = async (id) => {
try {
// const res = await proxy.$http.playerManage.downloadCompetitionProfile(id);
// 直接使用 axios 发送请求,并设置 responseType 为 blob
const apiBaseUrl = import.meta.env.VITE_BASE_URL_API;
const token = userStoreData.user.token;
const res = await axios.get(`${apiBaseUrl}/mark-resource/down/${id}`, {
responseType: "blob", // 设置响应类型为 blob(文件流)
headers: {
Authorization: ` ${token}`, // 添加 Authorization 头
},
});
if (res) {
// 获取响应头中的文件名
const contentDisposition = res.headers["content-disposition"];
let fileName = "资料文件.pdf"; // 默认文件名
if (
contentDisposition &&
contentDisposition.indexOf("attachment") !== -1
) {
const match = contentDisposition.match(/filename="(.+)"/);
if (match && match[1]) {
fileName = decodeURIComponent(match[1]); // 解码文件名
}
}
//创建一个Blob对象,并设置MIME类型为PDF
const blob = new Blob([res.data], { type: "application/pdf" });
//创建一个URL对象,用于指向Blob
const url = URL.createObjectURL(blob);
//创建一个影藏的a标签触发点击事件下载文件
const link = document.createElement("a");
link.href = url;
link.download = fileName; //设置下载文件名
link.click();
//释放URL对象
URL.revokeObjectURL(url);
}
} catch (error) {
showMessage({
type: "error",
message: "导出失败,请重试",
});
}
};