以下是使用 Vue 实现的通用下载方法:
// 文件下载方法
export function downloadFile(url, filename) {
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
// 通用下载方法
export function download(url, filename) {
if (!url || !filename) return
if (navigator.userAgent.indexOf('Trident') > -1) {
// IE下载
window.open(url)
} else {
// 非IE下载
const xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onload = function() {
if (xhr.status === 200) {
const blob = new Blob([xhr.response], { type: 'application/octet-stream' })
const blobUrl = URL.createObjectURL(blob)
downloadFile(blobUrl, filename)
URL.revokeObjectURL(blobUrl)
}
}
xhr.send()
}
}
使用方式:
download('http://example.com/file.pdf', 'example.pdf')
其中,downloadFile
方法用于创建一个下载链接并模拟点击下载,download
方法中通过判断浏览器类型,使用不同的下载方式。对于IE浏览器,使用window.open
方法打开一个新窗口下载;对于其他浏览器,使用XMLHttpRequest
获取文件流,并通过Blob
和URL.createObjectURL
方法,生成一个不同于原始文件URL的URL,然后调用downloadFile
方法下载。