---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)

通用下载方法

前端开发 蚂蚁 1474℃ 0评论

tansParams

 /**
   * 参数处理
   * @param {*} params  参数
   */
  export function tansParams(params) {
    let result = ''
    Object.keys(params).forEach((key) => {
      if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
        result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
      }
    })
    return result
  }

通用下载方法

// 通用下载方法
export function download(url, params, filename) {
  return service.post(url, params, {
    transformRequest: [(params) => {
      return tansParams(params)
    }],
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'blob'
  }).then((data) => {
    const content = data
    const blob = new Blob([content])
    if ('download' in document.createElement('a')) {
      const elink = document.createElement('a')
      elink.download = filename
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    } else {
      navigator.msSaveBlob(blob, filename)
    }
  }).catch((r) => {
    console.error(r)
  })
}

main.js

import { download } from '@/utils/request'
Vue.prototype.download = download

使用

 /** 导出按钮操作 */
    handleExport() {
      this.download('schedule/job/log/export', {
        ...this.queryParams
      }, `log_${new Date().getTime()}.xlsx`)
    }

转载请注明:有爱前端 » 通用下载方法

喜欢 (0)or分享 (0)