处理问题:
兼容不同浏览器的a标签点击下载
export const downLoadFile = ({
url,
fileName,
downType,
}: {
url: string
fileName: string
downType?: number
}) => {
const a = document.createElement('a')
// 接口请求
if (downType == 1) {
a.href = url
a.click()
} else {
//资源访问
const x = new XMLHttpRequest()
x.open('GET', url, true)
x.responseType = 'blob'
x.onload = function() {
//会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
const src = window.URL.createObjectURL(x.response)
a.href = src
if (fileName) {
a.download = fileName
}
a.click()
}
x.send()
}
}
使用:
downLoadFile({ url: url, fileName: fileName })