The World of Remnant

下载带token的二进制流和txt

let xmlRequest = new XMLHttpRequest();
    xmlRequest.open('GET', Const.HOST + '/settle/export?ids=' + param, true);
    xmlRequest.responseType = 'blob'; //这里是关键,它指明返回的数据的类型是二进制
    xmlRequest.setRequestHeader(
      'Authorization',
      'Bearer' + ((window as any).token ? ' ' + (window as any).token : '')
    );
    xmlRequest.onreadystatechange = function (e) {
      if (this.readyState == 4 && this.status == 200) {
        console.log(this.response);
        let down = document.createElement('a');
        down.href = window.URL.createObjectURL(this.response);
        down.download = '财务结算.xls';
        down.click();
        down.remove();
      }
    };
    xmlRequest.send(null);

补充:如何下载txt类型而不预览

downloadFile(link, filename) {
      var xhr = new XMLHttpRequest()
      xhr.responseType = 'blob'
      xhr.open('get', link, true)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          var status = xhr.status
          if (status === 0 || (status >= 200 && status < 400)) {
            let element = document.createElement('a')
            element.href = URL.createObjectURL(new Blob([xhr.response]))
            console.log('href', element.href)
            element.setAttribute('download', filename)
            element.click()
          }
        }
      }
      xhr.send()
    }