获取后端返回的文件流 前端进行文件下载
1. 在 utils 文件夹下创建 downloadFile.ts
import axios from "axios";interface Params {url: string;method: string;data: any;
}export const downLoadFileBlob = (params: Params) => {return axios({url: params.url, method: params.method, responseType: "blob", data: params.data, });
};
2. 使用
import { downLoadFileBlob } from "@/utils/downloadFile";
const downLoadFileFun = () => {const data = {dateType: 2,startTime: "2024-07-01 00:00:00",endTime: "2024-07-31 10:15:21",};downLoadFileBlob({url: "/api/v1/report/export/excel",method: "post",data: data,}).then((res)=>{if(res.status === 200){const debug = res.data;if(debug){const elink = document.createElement("a");const contentDisposition: string = res.headers.get("Content-Disposition");const filename: string = contentDisposition.split("filename=")[1];const tempName = decodeURIComponent(filename) elink.download = tempName;elink.style.display = "none";const blob = new Blob([debug], { type: "application/x-msdownload" });elink.href = URL.createObjectURL(blob);document.body.appendChild(elink);elink.click();document.body.removeChild(elink);}else{console.log("下载失败");}}})
};