用a标签下载文件没反应解决方法

251 阅读1分钟

背景

最近项目遇到一个问题:后端返回的oss文件地址用a标签下载,在谷歌浏览器某些版本上下载无反应,也有些文件地址因为同源策略浏览器无法直接下载,以下使用程序化下载解决这些问题

具体代码

export const download = async (fileUrl: string, name?: string) => {
  const a = document.createElement('a')
  const body = document.querySelector('body')
  a.style.display = 'none'
  body?.appendChild(a)
  const newUrl = URL.createObjectURL(await getFileBlobByUrl(fileUrl))
  a.href = newUrl
  a.download = name ?? getNameByFile(fileUrl)
  a.click()
  body?.removeChild(a)
  URL.revokeObjectURL(newUrl)
}
export const getNameByFile = (url: string) => {
  const arr = url.split('/')
  return arr.at(-1) ?? ''
}
async function getFileBlobByUrl (url: string): Promise<Blob | MediaSource> {
  let newUrl = url
  const { host, search } = new URL(url)
  if (host.includes('oss')) {
    const type = 'response-content-type=application/octet-stream'
    newUrl += search ? `&${type}` : `?${type}`
  }
  const response = await fetch(newUrl)
  const blob = await response.blob()
  return blob
}