前端根据url下载文件,支持跨域链接,解决a标签设置download失效问题

86 阅读1分钟

常规url导出文件

downloadFileForUrl(url: string, fileName?: string) {
    const link = document.createElement("a")
    link.href = url
    // download跨域情况会失效
    link.setAttribute("download", fileName)
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)
}

二级域名不一致也属于跨域,例如aaa.baidu.com和bbb.baidu.com

跨域导出文件的场景在工作中挺常见的,以下代码是支持跨域链接更改文件名的,可以一键复制使用

 downloadFileForCorsUrl(url: string, fileName?: string) {
    new Promise(resolve => {
        const xhr = new XMLHttpRequest()
        xhr.open("GET", url, true)
        xhr.responseType = "blob"
        xhr.onload = () => {
            if (xhr.status === 200) {
                resolve(xhr.response)
            }
        }
        xhr.send()
    }).then((blob: any) => {
        const link = document.createElement("a")
        link.href = window.URL.createObjectURL(blob)
        // 如果未设置文件名使用默认名称
        if(fileName){
            link.download = fileName
        }
        link.click()
        link.remove()
        window.URL.revokeObjectURL(url)
    })
}