下载大文件,前端轮询3s调一次接口且不超过3次。

441 阅读1分钟
## 下载导出文件时候,时常会遇到导出文件比较大,接口请求一遍下载不完的情况,
为了解决文件大下载的问题,考虑到每3秒调用一次A接口,如果A接口返回文件打包完成可以下载,
则调用B接口吊起下载功能。
//A接口 --按钮点击时
async exportPage() {
  let ids = []
  let params = {
    brand_task_id: this.$route.query.brand_task_id,
    nickname: this.form.nickname,
    user_role: this.form.user_role,
    status: this.form.status,
    flow_id: 3,
  }
  let data = await exportUser(params)
  this.fileData = data
  if (data) {
    var formData = new FormData()   //格式化formData,用于参数传递
    formData.append('file_name', data.file_name)
    formData.append('file_path', data.file_path)
    await this.exportLive(formData)
  }
},
//B接口
exportLive(param) {
  axios.post('/api/export/is_live', param).then(res => {
    console.log(res, '导出res')
    if (!res.data.data.status) {
      this.$message.success('导出成功')
      window.location.href = this.fileData.file_path
    } else {
      setTimeout(() => {
        this._limitFrequence(this.exportLive(param))
      }, 3000)
    }
  })
},
//封装方法函数_limitFrequence。限制最多请求三次!拒绝重复无限制调用
 _limitFrequence(fn, num = 3) {
      let result
      let time = 0
      return function() {
        if (time < num) {
          time++
          result = fn.apply(this, arguments)
        } else {
          console.log('超出次数')
        }
        return result
      }
    }