fangmd / blogsource

6 stars 0 forks source link

前端文件下载方案 #74

Open fangmd opened 2 years ago

fangmd commented 2 years ago

通过 a 标签

<a href="http://www.baidu.com" download="baidu.html">下载</a>

只能下载同源的文件,跨域的文件都是预览。

const a = document.createElement('a')
a.href = 'http://www.baidu.com'
a.download = 'baidu.html'
a.click()
fangmd commented 2 years ago

window.open

window.open('http://www.baidu.com', '_blank')

window.open('http://www.baidu.com', '_blank', 'download=baidu.html')

不能下载跨域文件

fangmd commented 2 years ago

blob

// 下载文件
export function downloadFile(obj, name, suffix) {
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}