前端批量下载遇到的问题
#前端 2023/03/16 02:59:14
在需要批量下载文件时,总是最后一个文件能够下载成功,在 Chrome Devtool 的网络请求里可以看到前面的文件请求状态是 canceled,代码如下。
const saveFile = (url, filename) => {
const link = document.createElement('a')
link.href = url
link.download = filename
link.click()
}
fileList.forEach((file) => {
saveFile(file.url, file.filename)
})
-
原因:把 a 链接当成一次网页导航,当点击 a 链接跳转时又重复点击该链接,浏览器此时会重置之前的跳转并重新计算,这就导致了之前的网络请求都被 canceled。
-
解决方法:使用 iframe 隐藏下载,但是缺点是会在 body 里面嵌入多个 iframe。
const saveFile = (url: string) => { const iframe = document.createElement('iframe') iframe.setAttribute('sandbox', 'allow-downloads allow-scripts') iframe.src = url iframe.setAttribute('style', 'display: none') document.body.appendChild(iframe) setTimeout(() => { iframe.remove() }, 1000) }
参考链接: