下载文件

1、封装

  /*
  * 下载文件
  * @param url:请求地址;
  * data:请求参数;
  * callback: 请求成功,回调操作
  * type:接收文件类型可在响应头中查找
  * */
  DownLoad(url, data, callback, type) {

    axios.post(url, data, { timeout: 5000000, responseType: 'arraybuffer' }).then(_res => {
      if (_res) {
        callback(true);
      } else {
        callback(false);
      }

      // 将 文件流 转成 blob 形式
      const blob = new Blob([_res.data], { type: type || 'application/vnd.ms-excel;' })

      // 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
      const a = document.createElement('a')

      // 生成文件路径
      let href = window.URL.createObjectURL(blob)
      a.href = href
      let _fileName = _res.headers['content-disposition'].split(';')[1].split('=')[1]
      // 文件名中有中文 则对文件名进行转码
      a.download = decodeURIComponent(_fileName + '.xls')
      // 利用a标签做下载
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(href);
    })
  },

 

2、调用

DownLoad(api.ebank_makeExcelReconciliationEBank, param, res=>{
  console.log("请求成功")
},'application/vnd.ms-excel;');

 

posted @ 2021-05-24 11:34  思猿客  阅读(166)  评论(0编辑  收藏  举报