获取后端返回的文件流 前端进行文件下载

发布于:2024-08-08 ⋅ 阅读:(61) ⋅ 点赞:(0)

获取后端返回的文件流 前端进行文件下载

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");

        //获取后端返回的文件名 一般在 Content-Disposition 上
        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("下载失败");
      }
    }
  })
};

网站公告

今日签到

点亮在社区的每一天
去签到