怎样使用axios下载Excel文件

2020-06-19  本文已影响0人  铁匠一锤治百病

废话少说,上code:

    axiosFunc({
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      }

      ...otherOptions
    })
    .then((res: any) => {
      const stream: any = res.data; // 后端用stream返回Excel文件
      const blob: any = new Blob([stream]);
      if (res.status !== 200) {
        // 非正常业务码,执行错误处理 
        // 注意:status字段名是团队自行定义的
      }

       // 前端获取业务码,成功执行正常业务
        const downloadElement = document.createElement('a');
        const href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
        const timeStamp = new Date().toString();
        const nameStr = timeStamp;
        downloadElement.download = nameStr; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
    });
  }
上一篇 下一篇

猜你喜欢

热点阅读