新版本的chrome会限制iframe下下载文件,除非在iframe中添加 sandbox="allow-downloads"
属性,否则都会报下面这个错误
Download is disallowed. The frame initiating or instantiating the download is sandboxed, but the flag ‘allow-downloads’ is not set. See https://www.chromestatus.com/feature/5706745674465280 for more details.
但是有些情况下,你不能去修改iframe上层的代码,包括iframe本身。那怎样可以下载呢?可以试试下面这个方法:
/**
* 通过链接下载文件
* @param url 文件链接
*/
export const downloadFile = async (url: string) => {
if (!document || !url) return false
// 获取文件名用
const b = document.createElement('a')
b.href = url
fetch(url).then((res) =>
res.blob().then((blob) => {
const a = document.createElement('a')
const blobUrl = window.URL.createObjectURL(blob)
a.href = blobUrl
a.download = decodeURIComponent(b.pathname?.split('/')?.pop())
a.click()
window.URL.revokeObjectURL(url)
a.remove()
b.remove()
})
)
return true
}