此方法为了解决 get请求 由于参数过多 造成的 文件无法下载的问题 /** * post post 方式文件下载 * @param fromData 下载需要传递的参数 * @param url 下载的路径 * @returns */ interface ArbitraryObject { [key: string]: any; } export function dowPostFiles(fromData: ArbitraryObject, url: string): Promise<any> { let sendUrl = getBaseAPI() + url; const lang = localStorage.getItem("lang"); return axios({ url: sendUrl, // 文件下载 URL method: "POST", responseType: "blob", // 这里我们需要服务器返回一个 Blob 对象 data: fromData, headers: { langType: lang ? lang : "zh_CN", "Content-Type": "application/json", token: sessionStorage.getItem("token"), getlocaluserid: sessionStorage.getItem("getlocaluserid"), getcookiduser: sessionStorage.getItem("getcookiduser"), }, }) .then((response: any) => { let filename = response.headers["content-disposition"]; const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; const matches = filenameRegex.exec(filename); if (matches !== null && matches[1]) { filename = matches[1].replace(/['"]/g, ""); } // 如果文件名被编码了,需要进行解码 filename = decodeURIComponent(filename); const url = URL.createObjectURL(new Blob([response.data])); const link = document.createElement("a"); link.href = url; link.setAttribute("download", filename); // <a>标签的 download 属性,指定下载的文件名 // 如果通过 new Blob 创建时没有指定类型或者服务器没有给Blob类型,这里要带后缀名 link.download = filename; link.hidden = true; document.body.appendChild(link); link.click(); setTimeout(() => { document.body.removeChild(link); window.URL.revokeObjectURL(url); }, 0); return new Promise((resolve, reject) => { resolve({ message: "下载成功", data: 200, }); }); }) .catch((err: any) => { return new Promise((resolve, reject) => { reject({ message: "下载失败", data: 500, }); }); }); }
调用方法
dowPostFiles({你要传递的参数对象}, 请求的url) .then(({ status, message: msg }: any) => { if (status === 200) { 请求成功 } }) .catch((err: any) => { 请求异常 });