VUE、Axios、AJAX、POST文件下载

/**
 *
 *  AJAX 获取文件流
 *  discretion 是否返回到回调函数上自行处理
 * onDownloadProgress 下载进度
 * @param {*} [opts={}]
 * @returns
 */
function RequestFile (opts = {}) {
  if (!opts.path || opts.path.trim() === '') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error('下载地址为空')
    } else {
      console.error('下载地址为空')
      return false
    }
  }
  const isPMS = getOptions().isPMS ? 1 : 0
  let isLoadingPlugin = true
  if (opts.isLoadingPlugin === false) isLoadingPlugin = false

  const config = {
    ...opts,
    url: `/api/${opts.path}`,
    method: opts.method || 'post',
    params: opts.params || {},
    data: opts.data || {},
    responseType: 'arraybuffer',
    timeout: MaxTimeOut,
    headers: {
      isPMS,
      filename: 'utf-8'
    }
  }

  if (isLoadingPlugin) operateLoading(true)

  axios(config)
    .then(res => {
      if (isLoadingPlugin) operateLoading(false)
      try {
        // 通用处理 -- 其实判断不到.. 流拿不到 res.data.retcodoe  可以考虑将Http status 改成401
        if (res.data.retcode && parseInt(res.data.retcode) === -41) {
          window.location.href = '/#/loginPage'
        } else {
          if (opts.discretion && opts.success) {
            opts.success.call(this, res.data)
          } else {
            const fname = getFileName(res.headers && res.headers['content-disposition'])
            const blob = new Blob([res.data], {
              type: opts.resContentType || 'application/vnd.ms-excel;charset=utf-8'
            })
            const downloadUrl = URL.createObjectURL(blob)
            urlToDownload(downloadUrl, fname)
            if (opts.success) opts.success.call(this)
          }
        }
      } catch (error) {
        throw new Error('download file error:' + (error ? error.message : ''))
      }
    })
    .catch(err => {
      if (isLoadingPlugin) operateLoading(false)
      if (opts.error) opts.error.call(this, err)
    })
}

// 根据返回流下载文件
function urlToDownload (downloadUrl = '', fname = '') {
  if (!downloadUrl || downloadUrl.trim() === '' || !fname || fname.trim() === '') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error('下载地址或文件名为空')
    } else {
      console.error('下载地址或文件名为空')
    }
  }
  const $ela = document.createElement('a')
  $ela.setAttribute('href', `${downloadUrl}`)
  $ela.setAttribute('download', fname)
  $ela.click()
  // window.open(downloadUrl)
}

// 提取文件名
function getFileName (str) {
  const isMatch = str.match(/filename\s*=(.+['.xls'|'.xlsx'])/ig)
  let name = 'member_export' + '.xlsx'
  if (isMatch && Array.isArray(isMatch) && isMatch[0]) {
    const _name = isMatch[0].replace(/[;|\s*|'=']/ig, '')
    name = _name.replace('filename', '')
  }
  return name
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容