1、创建blob响应类型的axios对象
const blobAxios = axios.create({
  responseType: \'blob\',
  timeout: 5 * 60 * 1000,
  paramsSerializer(p) {
    return Qs.stringify(p, { indices: false });
  }
});

blobAxios.interceptors.request.use((config) => {
  const token = authToken.token;
  if (token) {
    config.headers.Authorization = token;
  }
  return config;
});

2、使用blobAxios请求文件信息

  async function exportBusinessReport(url) {
      const response = await blobAxios.get(url);
      return downloadResponse(response);
  }
3、生成a标签实现真正的下载
function downloadFile(url, filename) {
  const   = document.createElement(\'a\');
   .href = url;
   .setAttribute(\'download\', filename);
  document.body.appendChild( );
   .click();
  document.body.removeChild( );
}
//获得文件名
function retriveFileName(response, defaultName = \'file\') {
  const disposition = response.headers[\'content-disposition\'];
  const matchGroup = /filename=\"?([^\"^;]+)\"?/.exec(decodeURIComponent(disposition));
  if (_.isArray(matchGroup)) {
    return matchGroup[1];
  }

  return defaultName;
}

 function downloadResponse(response, exportFileName) {
  const url = window.URL.create URL(new Blob([response.data]));
  const filename = exportFileName || retriveFileName(response);
  const notAllowedFileType = \'application/json\';
  if (response.data.type !== notAllowedFileType) {
    downloadFile(url, filename);
  } else {
    throw new StandardError({ message: \'加载异常,请联系开发查看原因\' });
  }
}

 

收藏 打印