有时候会有下载excel的需求,如果后端直接给链接,我们下载就很方便
downLoadByLink(link: string) {
const CreateA = document.createElement('a')
CreateA.href = link
CreateA.download = ''
document.body.appendChild(CreateA)
CreateA.click()
document.body.removeChild(CreateA)
}
}
但是大部分情况是按需下载,实时下载,前端选择需要下载的数据,后端返回数据流,然后我们处理后导出
responseType: 'blob'
if (response.headers && response.headers['content-disposition']) {
return response
}
function downloadFile(response) {
const str = decodeURIComponent(data.headers['content-disposition'])
const fileName = str.split('filename=')[1]
const content = data.data
const blob = new Blob([content])
if ('download' in document.createElement('a')) {
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, fileName)
}
}