vue中下载.csv文件

727 阅读2分钟

1 请求后台接口 获取到文件流的内容

```

exportFile(url) {      var that = this;      const token = localStorage.getItem("access-token");      const API = axios.create({        baseURL: baseUrl,      });      API({        method: "get",        url: url,        headers: { "access-token": token },        responseType: "blob",      })        .then((response) => {          console.log(response);          if (response.status == 200) {            if (this.MyBrowserIsIE()) {              var data = new Blob([response.data])              window.navigator.msSaveBlob(data, that.getFileName());  //response为接口返回数据,这里请求的时候已经处理了,如果没处理需要在此之前自行处理var data = new Blob([response.data]) 注意这里需要是数组形式的,fileNm就是下载之后的文件名            }            that.download(response);          } else {            this.$message.error(response.statusText);          }        })        .catch((error) => {          this.$message.error(error);        });    },

```

判断浏览器是否为ie浏览器

(```)

MyBrowserIsIE() {      let isIE = false;      if (        navigator.userAgent.indexOf("compatible") > -1 &&        navigator.userAgent.indexOf("MSIE") > -1      ) {        isIE = true;      }      if (navigator.userAgent.indexOf("Trident") > -1) {        isIE = true;      }      return isIE;    },

(```)

2 对请求到的文件流进行下载

(```)

download(data) {      if (!data) {        return;      }      var blob = new Blob([data.data], {        type:          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",      });      var downloadElement = document.createElement("a");      var href = window.URL.createObjectURL(blob); // 创建下载的链接      downloadElement.href = href;      let fileName = this.getFileName();      downloadElement.download = fileName; // 下载后文件名      document.body.appendChild(downloadElement);      downloadElement.click(); // 点击下载      document.body.removeChild(downloadElement); // 下载完成移除元素      window.URL.revokeObjectURL(href); // 释放掉blob对象    },

(```)

这里有个坑,被我踩到了。

在测试环境的时候 ,我输出data也就是请求返回的response是能过看到headers里面的content-description的,这里为了和后台订单导出文件名一致,我一开始是使用的content-description里面的文件名,到生产环境headers里面只有content-type,没有其他值了,我找了一下资料,发现没有人写 ... 所以我目前也不知道为啥,等有时间找找资料,可以蹲后续.... 所以我自己写了个方法获取到当前年月日+六位数的随机数字 ,自己造了个文件名

(```)

getFileName() {      var date = new Date();      var year = date.getFullYear();      var month = date.getMonth() + 1;      var day = date.getDate();      if (month < 10) {        month = "0" + month;      }      if (day < 10) {        day = "0" + day;      }      var nowDate = year + "-" + month + "-" + day;      var randomStr = "";      for (let i = 0; i <= 6; i++) {        const num = Math.floor(Math.random() * 10);        randomStr += num;      }      return `爆单订单报表_${nowDate}_${randomStr}.csv`;    },

(```)

这样就可以下载下来了,我看有的帖子说要判断一下是不是IE浏览器,我这个代码没有判断也可以下载了,不知道是不是版本比较高,好啦 ,有了这三段代码就可以愉快的下载文件啦~