axios + blob + a标签下载文件

分享一个axios请求接口,拿到二进制数据后下载zip文件的方法:

  export const downloadZip = (url, method = 'post', data, options = {contentType:"multipart/form-data",responseType:'blob'}, name='未命名') => {
  let loadingInstance = Loading.service({ fullscreen: true, text:'下载中,请稍等......' });
  let params = {};
  if (method.toLowerCase() === 'get') { // 根据不同情况处理参数
    params = {params: {...data}}
  } else if (options.contentType === 'multipart/form-data') {
     params = {data}
  } else {
    params = {data: {...data}}
  }
  axios({
    url,
    method,
    responseType: options.responseType,
    ...params,
    headers: {
      TOKEN: getToken(), // 此处根据项目设定
      "Content-Type": options.contentType
    }
  }).then((response) => {
    const blob = new Blob([response.data], { type: "application/zip" }); // 此处type可以作为参数传入
    if (blob.size < 500) {
      Message.error('暂无数据')
      loadingInstance.close()
      return
    }
    const url = window.URL.createObjectURL(blob);
    const LINK = document.createElement('a');
    LINK.href = url;
    LINK.setAttribute('download', name);
    document.body.appendChild(LINK);
    LINK.click();
    LINK.remove(); // 释放内存
    URL.revokeObjectURL(url) 
    setTimeout(()=> {
      loadingInstance.close()
    }, 2000)
  }).catch(err=>{
    loadingInstance.close()
  });
}

以上axios().then().catch()链式写法 可以 用 async await 改写,很简单这里就先不做修改了

原文地址:https://www.cnblogs.com/fq1017/p/13408384.html