前端使用a标签下载非同源文件(备选方案)

发布时间 2023-12-29 13:50:51作者: LiangSenCheng小森森

原理:

下载文件Blob,再把Blob转为本地链接,以实现跨域变同域,最后使用a标签实现下载;

优缺点:

● 优点:能达到下载跨域文件的目的;

● 缺点:不适用于大文件,大文件体验较差;

示例:

使用fetch把文件下载下来,然后URL.createObjectURL转为本地链接,最后使用a标签下载;

/**
 * 跨域文件下载
* @param url  附件地址
* @param download  附件可以预览或者下载
*/

// 获取文件名
// 适用URL格式类似为:http://abc.com/xxx-file.jpg
const getFileName = (url) => {
  const name = url.split('/').pop()
  return name.pop()
}

// 下载
export const fileDownload = (url) => {
  const filename = getFileName(url)
  fetch(url)
    .then(response => {
      return response.blob()
    })
    .then(blob => {
      const blobUrl = window.URL.createObjectURL(blob)
      // 创建a标签下载
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobUrl
      tempLink.setAttribute('download', filename)
      document.body.appendChild(tempLink)
      tempLink.click()
      setTimeout(() => {
        URL.revokeObjectURL(blobUrl)
        document.body.removeChild(tempLink)
      })
    })
}

原文链接:

前端使用a标签下载非同源文件(备选方案)