2021-04-28 前端文件流转化(转成Excel)

需求:公司的文件传输,后端传给前端是一个流文件,也就是一个blob文件。需要转换成对应的附件。

js:

export function exportSearchList(dowLoadFileName, result) {
  const blob = new Blob([result]);
  const fileName = dowLoadFileName + '.xlsx';
  // 判断浏览器
  var brower = '';
  if (navigator.userAgent.indexOf('Edge') > -1) {
    brower = 'Edge';
  }

  if ('download' in document.createElement('a')) {
    // 非IE下载
    if (brower == 'Edge') {
      navigator.msSaveBlob(blob, fileName);
      return;
    }
    const elink = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    // 释放URL 对象
    document.body.removeChild(elink);
  } else {
    // IE10+下载
    navigator.msSaveBlob(blob, fileName);
  }

}

使用时:

exectexport() {
      let searchData = {};
      if (this.searchDataTime) {
        searchData.beginDate = this.searchDataTime[0];
        searchData.endDate = this.searchDataTime[1];
      }
      searchData.phone = this.searchData.tel;
      axios({
        url: "/cms-rest/api/messageManagement/download",
        method: "post",
        responseType: "blob",
        data: searchData,
      })
        .then((result) => {
          util.exportSearchList("留言管理", result.data);
        })
        .catch((error) => {
          throw error;
        });
    },

综上!记录一下

你可能感兴趣的:(JS且走且珍惜,vue,javascript)