【前端实用工具】——前端获取文件流导出-GET/POST方法

前端获取文件流导出

  • 一.POST方法
  • 二.GET方法

一.POST方法

axios({
      method: 'post',
      url: url,//接口地址
      data: { id: id},//入参
      responseType: 'arraybuffer',//根据接口来
      headers: {
        accept: '*/*',
        'Content-Type': 'application/json',
        Authenticator: Authenticator//token
      }
    }).then((res) => {
      var blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8;' });
      // FileReader主要用于将文件内容读入内存
      let a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = 'name.xlsx';//保存文件名
      a.click(); // 模拟点击a标签
      window.URL.revokeObjectURL(a.href);
    })

二.GET方法

axios({
      method: 'get',
      url: url,//接口地址,参数直接拼在url后面
      responseType: 'arraybuffer',
      headers: {
        accept: '*/*',
        'Content-Type': 'application/json',//根据接口来
        Authenticator: Authenticator//token
      }
    }).then((res) => {
      var blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8;' });
      // FileReader主要用于将文件内容读入内存
      let a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = 'name.xlsx';//保存文件名
      a.click(); // 模拟点击a标签
      window.URL.revokeObjectURL(a.href);
    })

axios也可以,但是使用的时候有失效的情况,也可以用下面这段,批量下载推荐用下面这种方式

	let Authenticator = localStorage.getItem('authenticator');
    let dataSource = []
    dataSource.push(url+"?Authenticator=" + Authenticator);//url-接口地址
    //for (let i = 0; i < dataSource.length; i++) {//批量下载再加一层循环
    let iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.style.height = '0px';
    iframe.src = dataSource[0];//批量下载dataSource[0]换成dataSource[i]
    document.body.appendChild(iframe);
    setTimeout(() => {
      iframe.remove(); //下载后移除
    }, 10000);
    //}

你可能感兴趣的:(前端实用工具,前端)