1、后端直接返回文件服务器地址,前端创建a标签模拟
export function downloadFileUrl (url, fileName) {
const elink = document.createElement('a')
elink.href = url
elink.setAttribute('download', fileName)
elink.style.display = 'none'
document.body.appendChild(elink)
setTimeout(() => {
elink.click()
document.body.removeChild(elink)
}, 66)
}
上述方法参数url表示后端返回的文件地址,fileName表示下载的文件名称,本人查询了download属性的兼容性,的确ie11及一下不兼容,图片和pdf时会直接打开,压缩包文件的话全部能正常下载(ie是11及以上),直接打开的图片和pdf这是浏览器机制问题。
2、后端返回二进文件流,前端使用blob进行文件下载
export function downloadFileStream (fileStream, name, extension, type = '') {
const blob = new Blob([fileStream], {type})
const fileName = `${name}.${extension}`
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 {
// 兼容IE10+下载
navigator.msSaveBlob(blob, fileName)
}
}
返回参数注释:fileStream返回流,name文件名称,extension文件后缀类型, type为文件类型
excel的话为application/vnd.ms-excel
注意axios请求时返回类型为responseType = 'blob'