js实现文件流下载

4,006 阅读1分钟

获取文件流

  downloadFile() {
    const that = this
    const ajax = new XMLHttpRequest()
      // 很关键
    ajax.responseType = 'blob'
    const url: string = 'urlstr';
    ajax.open("GET",url,true)
    ajax.setRequestHeader('Authorization','Bearer ' + localStorage.getItem('token'))
    ajax.onreadystatechange = function(){
        if(this.readyState == 4) {
          if(this.status == 200) {
            if(this.response.type == "application/octet-stream"){
                const fileType: string = "application/octet-stream";
                const fileName: string = 'fileName.cpt';
                that.downloadHandler(this.response, fileName, fileType);
            }else{
                // 错误提示
                // that.$message.warning('资源下载异常!')
            }
          }
        }else if (this.readyState == 2) {
          if(this.status == 200) {
              this.responseType = "blob"
          } else {
              this.responseType = "text"
          }
        }
    }
    ajax.send(null);
  }

保存文件

  downloadHandler(data, fileName, type) {
  	// 匹配任意文件类型:type : "application/octet-stream"
    let blob = new Blob([data], {type:type||"application/octet-stream"});
    // 获取heads中的filename文件名
    let downloadElement = document.createElement('a');
    // 创建下载的链接
    let href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    // 下载后文件名
    downloadElement.download = fileName;
    document.body.appendChild(downloadElement);
    // 点击下载
    downloadElement.click();
    // 下载完成移除元素
    document.body.removeChild(downloadElement);
    // 释放掉blob对象
    window.URL.revokeObjectURL(href);
  }