点击下载

37 阅读1分钟
// 文件下载
export const downloadFile = (fileUrl, fileName = new Date().valueOf().toString()) => {
  fetch(fileUrl).then(res =>
    res.blob().then(blob => {
      let a = document.createElement('a')
      let url = window.URL.createObjectURL(blob)
      a.href = url
      a.download = fileName
      a.click()
      window.URL.revokeObjectURL(url)
    })
  )
}

downFile() {
      const config = {}
      config.responseType = 'blob'
      axios
        .get(
          'https://img1.xxxxxxxxxxxxxxx?w=800&h=500',
          config
        )
        .then((res) => {
          const blob = new Blob([res.data]) // 将字节流(字符流)转换为 blob 对象
          let url = window.URL.createObjectURL(blob)
          //  解决 ie 不支持下载 blob资源
          if ('msSaveOrOpenBlob' in navigator) {
            window.navigator.msSaveOrOpenBlob(blob, 'ceshi.jpg')
            return
          }
          let ele = document.createElement('a')
          ele.style.display = 'none'
          ele.href = url
          ele.download = 'ceshi.jpg'
          document.body.appendChild(ele)
          ele.click()
          document.body.removeChild(ele) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        })
    },