axios下载后台的文件流(含错误处理)

前端下载后台传入很大的一个文件流

大致思路: 设置请求头字段 responseType为blob,将获取的数据(zip文件流)转为blob格式,创建下载链接最后用a标签下载即可

  • 具体实现
// suffix为 ?a=1&b=2 类似的请求参数; fileName为下载文件名
function saveAs(suffix = "", fileName: string) {
      const url = _this.exportUrl+suffix;
      _this.loading = true;
      axios({
          method: 'get',
          url: url,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization: _this._state.userInfo.token
          },
          responseType: 'blob', // arraybuffer/blob 这样会导致返回的始终是blob文件
        }).then(res => {
          const contentType = res.headers['content-type'];
          if(res.status === 200) {
            if(contentType == 'blob') { // 返回文件对象
              const data = res.data;

              const blob = new Blob([res.data], { type: 'application/zip;charset=utf-8'} );
              if ('download' in document.createElement('a')) { // 非IE下载
                const elink = document.createElement('a');
                elink.target = "hrefTemplate"; // 指向上面的iframe框架(防止跳转至空白页),可有可无
                elink.download = fileName+".zip";
                elink.href = URL.createObjectURL(blob)
                elink.click()

                _this.loading = false;
                URL.revokeObjectURL(elink.href) // 释放URL 对象
              } else { // IE10+下载
                navigator.msSaveBlob(blob, fileName)
              }
            }
            else {
              _this.$message.error(`暂无 ${ province }${ city } 相关数据`)
              _this.loading = false;
            }
          }
          else {
            _this.$message.error(`下载失败 ---${ res.status }`)
            _this.loading = false;
          }
        }).catch(err => {
          _this.$message.error(`下载失败 ---${ String(err) }`)
          _this.loading = false;
        })
    }

上面的fileName我以当前时间命名的,以下为时间函数(返回类似 202010191522)

export function nowTime(time = +new Date()) {
  //格林威治时间+8h
  const date = new Date(time + 8 * 3600 * 1000);
  // 以下是精确到s,如果毫秒,substr(0, 23),
  return date.toJSON().substr(0, 20).replace('T', '').replace(/-|\.|:/g, '');
}

版权声明:本文为qq_39370934原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。