下载 导出文件详细教程

171 阅读1分钟

axios下载导出文件为excel,xlxs

定义点击事件

Wei_yasuo() {
      axios
        .post(
          "/qxgk/api/wqx/data/historyData/export",
          {
            startTime: this.startTime,
            endTime: this.endTime,
            pagesize: this.pagesize,
            pagenum: this.pagenum,
            region: this.WEI_value1,
            voltageLevel: this.WEI_value2,
            line: this.WEI_value3,
            name: this.WEI_value4
          },
          {
            responseType: "blob"
          },
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8"
            }
          }
        )
        .then(res => {
          this.download(res);//调用download()方法下载
        });
    },
调用download()方法下载
    download(res) {
      //headers请求头的乱码数据转换为中文
      // debugger
      // var headStr = decodeURI(res.headers["content-disposition"]);
      const fileName = decodeURI(
        res.headers["content-disposition"].split(";")[1].split("=")[1]
      );

      //console.log(typeof data.data, "data");
      let blob = new Blob([res.data], {
        type: "application/vnd.ms-excel"
      }); // res就是接口返回的文件流了
      let objectUrl = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = objectUrl;
      //a.download = "自动站.xlsx"; //后缀名一定要写对,不然会导致文件损坏,打不开 自定义文件名
      a.setAttribute("download", fileName); //获取后端文件名
      a.click();
      a.remove();
      URL.revokeObjectURL(objectUrl); // 释放内存
    },

111.png