虚拟dom模拟a标签下载

867 阅读1分钟
  /**
   * 虚拟dom 模拟 a 标签下载
   * data:服务端返回blob数据流 fileName点击下载时生成的文件名
   */
  function downloadFile (data, fileName) {
    const a = document.createElement('a')
    document.body.appendChild(a)
    a.style = 'display: none'
    const blob = new Blob([data], {
      type: 'application/octet-stream'
    })
    const url = window.URL.createObjectURL(blob)
    a.href = url
    if (fileName) {
      a.download = fileName
    }
    a.click()
    window.URL.revokeObjectURL(url)
  }

  /**
   * 虚拟dom 模拟 a 标签下载
   * url:服务端返回url地址 fileName点击下载时生成的文件名
   */
  function downloadUrlFile (url, fileName) {
    const a = document.createElement('a')
    document.body.appendChild(a)
    a.style = 'display: none'
    a.href = url
    if (fileName) {
      a.download = fileName
    }
    a.click()
    window.URL.revokeObjectURL(url)
  }