前端下载有两种常用方式,一种是打开新页签触发下载,另一种是在本页面先下载文件转换为二进制再下载。
一、新建标签页的方式
function downLoad (downLoadUrl) {
let a = document.createElement('a')
//是否支持download(H5属性)
if (a.download) {
// 必须设置 href 属性,可以使文件名
a.href = downLoadUrl
if (document.createEvent) {
var evObj = document.createEvent('MouseEvents')
evObj.initEvent(
'click',
true,
true,
window,
1,
12,
345,
7,
220,
false,
false,
true,
false,
0,
null
)
a.dispatchEvent(evObj)
} else if (document.createEventObject) {
a.fireEvent('onmousemove')
}
} else {
window.open(downLoadUrl, '_blank')
}
}
二、当前页下载
function postDownLoad (data) {
axios({
baseURL,
method: 'get',
url: data.documentUrl,
headers: {
Authorization: utils.getSS('Authorization') || null,
'Content-type': 'application/json;charset=UTF-8'
},
responseType: 'blob',
timeout: 10000,
data: {}
}).then(res => {
const blob = new Blob([res.data])
// 兼容不同浏览器的URL对象
const url = window.URL || window.webkitURL || window.moxURL
// 兼容IE
if ('msSaveOrOpenBlob' in navigator) {
window.navigator.msSaveOrOpenBlob(blob, data.fileName)
return
}
// 创建下载链接
const downloadHref = url.createObjectURL(blob)
// 创建a标签并为其添加属性
let downloadLink = document.createElement('a')
downloadLink.href = downloadHref
downloadLink.download = data.fileName || data.contractName || '未知文件.txt'
// 触发点击事件执行下载
downloadLink.click()
}).catch(_ => {})
}