工作需要,不多赘述,直接记录,留作笔记,有待完善
1、window.open,window.location.href
window.open(url, '_blank')
window.location.href = url
location.href = url // 这样也行
2、a 标签
<a href="url" download="改下载文件名" target=“_blank”></a>
3、fetch
往往下载时需要改变文件名,open 方式 或 直接用 a 标签就做不到了
const link = document.createElement('a')
fetch(url)
.then((res) => res.blob())
.then((blob) => {
link.href = URL.createObjectURL(blob)
link.download = fileName
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
4、new Blob()
有时需要下载后端返回的文件流
interface(condition).then((res) => {
const aLink = document.createElement('a')
let blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' })
aLink.href = URL.createObjectURL(blob)
aLink.download = 'xxxx.xlsx'
aLink.click()
document.body.appendChild(aLink)
})