前端下载二进制流数据

这里以axios请求演示:

 axios({
        url: url,
        method: 'get',
        params: parameter,
        headers: signHeader,
        //指定返回的数据类型
        responseType: 'arraybuffer',
      }).then(res=>{
        //application/vnd.openxmlformats-officedocument.wordprocessingml.document 》》》docx类型
        var blob = new Blob([res],
          {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
        var downloadElement = document.createElement('a');
        //创建下载的链接
        var href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        //下载后文件名
        downloadElement.download = 'hh.docx';
        document.body.appendChild(downloadElement);
        //点击下载
        downloadElement.click();
        //下载完成移除元素
        document.body.removeChild(downloadElement);
        //释放掉blob对象
        window.URL.revokeObjectURL(href);
        //加载loading
        this.downloadLoading = false;
      })
    }

说明:application/vnd.openxmlformats-officedocument.wordprocessingml.document  》》》指定文件类型

其他类型的文件参考:

  https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

有时候会发生后台校验,返回提示信息,这时候返回json数据,所以修改一下:

try里面处理json数据,catch里处理流数据

axios({
        url: url,
        method: 'get',
        params: parameter,
        headers: signHeader,
        //指定返回的数据类型
        responseType: 'arraybuffer',
      }).then(res=> {
        try {
          let enc = new TextDecoder('utf-8')
          let data = JSON.parse(enc.decode(new Uint8Array(res)))
          this.downloadLoading = false;
          this.$message.warning(data.message)
        } catch (err) {
          //application/vnd.openxmlformats-officedocument.wordprocessingml.document 》》》docx类型
          var blob = new Blob([res],
            { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8' });
          var downloadElement = document.createElement('a');
          //创建下载的链接
          var href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          //下载后文件名
          downloadElement.download = '请示.docx';
          document.body.appendChild(downloadElement);
          //点击下载
          downloadElement.click();
          //下载完成移除元素
          document.body.removeChild(downloadElement);
          //释放掉blob对象
          window.URL.revokeObjectURL(href);
          //加载loading
          this.downloadLoading = false;
        }
      })
    }

 

posted @ 2021-09-20 16:15  来一杯可乐  阅读(224)  评论(0编辑  收藏  举报