a标签下载 url/blod

75 阅读1分钟

a标签下载 url/blod

下载url

  • 链接直接下载。
  • txt、图片png... 会直接网页加载 无法下载。
  • 无法改名(跨域问题,网传未试验)
const downloadFile = () => {  
    const link = document.createElement('a')
    // 设置下载地址
    link.href = url
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}

下载blod

  • 可用改名
  • 各种格式直接下载
//通过文件下载url拿到对应的blob对象
const getBlob = (url) => {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response)
      }
    }
​
    xhr.send()
  })
}
//下载文件   js模拟点击a标签进行下载
const saveAs = (blob:any, filename:any) => {
  var link = document.createElement('a')
  link.href = window.URL.createObjectURL(blob)
  link.download = filename
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
const handlePreview = async () => {
  const url = url
  const textName = '文件名'
  const res = await getBlob(url) //url 转 blob
  saveAs(res, textName) // 下载
}