纯前端实现文件的下载

98 阅读1分钟

1.Blob 转换下载

 downloadFile() {
  var url = './static/test.docx'
  var xhr = new XMLHttpRequest()
  console.log('数据信息', xhr, url)
  xhr.open('GET', url, true) // 异步
  xhr.responseType = 'blob' // blob 类型
  xhr.onload = function() {
    if (xhr.status !== 200) {
      alert('下载异常!')
      return
    }
    if (window.navigator.msSaveOrOpenBlob) {
    // IE
      navigator.msSaveBlob(xhr.response, filename)
    } else {
      var newUrl = window.URL.createObjectURL(xhr.response)
      var a = document.createElement('a')
      a.setAttribute('href', newUrl)
      a.setAttribute('target', '_blank')
      a.setAttribute('download', '智能决策闭环BPM子任务用户操作手册.docx') // 自定义文件名(有效)
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  }
  xhr.send()
}

<a class="systemDownload" @click="downloadFile"><i class="el-icon-download"></i></a>

2.a标签下载

1.<a class="systemDownload" href="./static/test.docx" download="test.docx" >
  <i class="el-icon-download"></i>
</a>
2.<a class="systemDownload" @click="downloadFile"><i class="el-icon-download"></i</a>
 downloadFile() {
  const a = document.createElement('a')
  a.href = './static/bpm.docx'
  console.log(a.href)
  a.setAttribute('download', 'test.docx')
  a.click()
  a.remove()
},

总结

同源就直接使用 <a> download 下载,跨域就先获取 blob,用 createObjectURL 或 readAsDataURL 读取链接,再用 <a> download 下载。

学习博客:https://blog.csdn.net/Ed7zgeE9X/article/details/131650763