JS下载文件两种方式

JS下载文件两种方式

  • 态静态资源下载,直接 window.location.href=URLwindow.open(URL) 或 创建 a 标签并指定 a.href=URL 模拟点击进行下载

  • 另外一种则是二进制下载文件,首先将 XMLHttpRequest.responseType 设置为 blob,然后用 URL.createObjectURL()Blob 处理返回二进制流,然后使用 a 标签进行下载

// 这里采用Axios.js做请求
// Axios Docs:https://www.runoob.com/vue2/vuejs-ajax-axios.html
export function downloadExcel({method = 'GET', url, responseType = 'blob', params, data, fileName = '表格', suffix = 'xlsx'}) {
  const option = {method, responseType, url}
  if (method === 'GET') {
    option.params = params
  } else if (method === 'POST') {
    option.data = data
  }
  // request(option).then((response) => {
  axios(option).then((response) => {
    // 判断接口是否正常响应了二进制流,没有则抛错
    if (!response || response.msg) {
      return alert(response.msg || '接口未响应消息')
    }
    //  如果支持微软的文件下载方式(ie10+浏览器)
    if (window.navigator.msSaveBlob) {
      try {
        // 只要显示下载栏,就是返回true,若果失败则返回false
        navigator.msSaveBlob(new Blob([response]), `${fileName}.${suffix}`)
      } catch (e) {
        console.log(e)
      }
    } else {
      // 兼容不同浏览器的URL对象
      const URL = window.URL || window.webkitURL || window.moxURL;
      // 创建下载链接,直接使用响应头中的type,就是文件后缀名
      const href = URL.createObjectURL(new Blob([response], {type: response.type}))
      // 创建a标签并为其添加属性
      const a = document.createElement('a')
      a.href = href
      a.download = `${fileName}.${suffix}`
      document.body.appendChild(a)
      a.click() //触发点击事件执行下载
      a.style.dispaly = 'none'
      const timer = setTimeout(function () {
        a.remove() // document.body.removeChild(a)
        // 释放blob对象
        URL.revokeObjectURL(href)
        clearTimeout(timer)
      }, 1000)
    }
  })
}

网站资源

URL.createObjectURL:https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL

Blob:https://developer.mozilla.org/zh-CN/docs/Web/API/Blob

responseType:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/responseType

msSaveBlob:https://developer.mozilla.org/en-US/docs/Web/API/Navigator/msSaveBlob

posted on 2021-06-16 10:33  我是何平  阅读(3959)  评论(0编辑  收藏  举报