vue 文件流导出获取后端文件名称

response.addHeader("Content-Disposition","attachment;filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
在后端的接口中开放这个这个响应头,前端的response就可以获取到了

import axios from "axios"; import { ElNotification } from "element-plus"; import { useUserStore } from "@/store/modules/user"; let baseUrl = import.meta.env.VITE_APP_PREFIX; export const exportFile = (url, params) => { const userStore = useUserStore(); return new Promise((resolve, reject) => { axios({ url: baseUrl + url, method: "post", responseType: "blob", data: params, headers: { authorization: userStore.token ? `Bearer ${userStore.token}` : "", }, }).then((response) => { let dispositionStr = response.headers["content-disposition"]; if (dispositionStr == null || dispositionStr === "") { ElNotification({ title: "温馨提示", message: "导出失败", type: "error", }); reject("下载失败!"); return; } // 获取文件名 let dispositionArr = dispositionStr.split(";"); let fileName = decodeURIComponent(dispositionArr[1]); fileName = fileName.split("=")[1]; const blob = new Blob([response.data], { type: "application/vnd.ms-excel", }); const link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); link.download =fileName; document.body.appendChild(link); link.click(); window.setTimeout(function () { window.URL.revokeObjectURL(blob); document.body.removeChild(link); ElNotification({ title: "温馨提示", message: "导出成功", type: "success", }); resolve() }, 0); }); }); };

 

posted @ 2022-10-31 19:52  浮生如梦似离殇  阅读(911)  评论(0编辑  收藏  举报