当使用a标签下载文件时,如果同源可以直接下载,但是不同源时,download属性会无效,且会发生跳转行为
同源
function downloadFile(url) {
const link = document.createElement('a')
link.href = url
link.download = new Date().getTime()
link.click()
link.remove()
}
不同源
import { Loading } from 'element-ui'
downloadFile(url) {
const loading = Loading.service({
text: '下载文件中,请耐心等待...',
background: 'rgba(0, 0, 0, 0.4)'
})
fetch(url).then(response => response.blob()).then(res => {
const blobUrl = URL.createObjectURL(res)
const link = document.createElement('a')
link.href = blobUrl
link.download = new Date().getTime()
link.click()
link.remove()
URL.revokeObjectURL(blobUrl)
loading.close()
})
}