需要请求头的流文件通用下载模板(ts版)

173 阅读1分钟
// 需要添加的请求头
const getHeaders = () => {
  return {
    XXX_TOKEN1: 'xxx', // 通常从localStorage取
    XXX_TOKEN2: 'xxx', // 通常从localStorage取
  };
};

// 有些图片、封面图、excel需要鉴权才能看,就是说要加上headers
function downloadWithHeaders(url: string, method: string = 'GET', cb: { (blobUrl: string): void }) {
  const xhr = new XMLHttpRequest();
  // GET、POST请求,请求路径url,async(是否异步)
  xhr.open(method, url, true);
  // 设置请求头参数的方式,如果没有可忽略此行代码
  const headers = getHeaders();
  for (const [k, v] of Object.entries(headers)) {
    xhr.setRequestHeader(k, v);
  }
  // 设置响应类型为 blob
  xhr.responseType = 'blob';
  // 关键部分
  xhr.onload = function onload() {
    // 如果请求执行成功
    if (this.status === 200) {
      const blob = this.response;
      const blobUrl = window.URL.createObjectURL(blob);
      cb(blobUrl);
    } else {
      console.error(`【下载报错】method:${method}, url:${url}, headers:${headers}`);
    }
  };
  // 发送请求
  xhr.send();
}

// 下载excel
export function downloadExcelWithHeaders(
  url: string,
  method: string = 'GET',
  fileName: string = '文件.xlsx',
) {
  const cb = (blobUrl: string) => {
    const a = document.createElement('a');
    a.download = fileName;
    a.href = blobUrl;
    a.click();
    window.URL.revokeObjectURL(blobUrl);
  };
  downloadWithHeaders(url, method, cb);
}

// 下载图片并展示在某元素地方
export function downloadImageWithHeaders(url: string, method: string = 'GET', el: HTMLElement) {
  const cb = (blobUrl: string) => {
    const img = document.createElement('img');
    img.style.width = '100%';
    img.style.height = '100%';
    img.src = blobUrl;
    el.appendChild(img);
    window.URL.revokeObjectURL(blobUrl);
  };
  downloadWithHeaders(url, method, cb);
}