vue下载实现
Vue 下载实现方法
在 Vue 项目中实现文件下载功能,可以通过以下几种方式实现:
前端直接触发下载
使用 <a> 标签的 download 属性实现文件下载:
<template>
<a :href="fileUrl" download="filename.ext">下载文件</a>
</template>
<script>
export default {
data() {
return {
fileUrl: '/path/to/file.ext'
}
}
}
</script>
通过 Blob 对象下载
对于需要动态生成或从 API 获取的文件内容,可以使用 Blob 对象:
downloadFile(content, filename) {
const blob = new Blob([content])
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = filename
link.click()
URL.revokeObjectURL(link.href)
}
axios 请求后端文件
当文件需要从后端 API 获取时:
axios({
url: '/api/download',
method: 'GET',
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'file.pdf')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
服务器端设置响应头
确保后端 API 设置了正确的响应头:
Content-Disposition: attachment; filename="file.ext"
Content-Type: application/octet-stream
文件下载进度显示
使用 axios 的 onDownloadProgress 显示下载进度:
axios({
url: '/api/download',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
console.log(percentCompleted)
}
}).then(response => {
// 处理下载
})
大文件分块下载
对于大文件可以实现分块下载:

async function downloadLargeFile(url, fileName) {
const response = await fetch(url)
const reader = response.body.getReader()
const contentLength = +response.headers.get('Content-Length')
let receivedLength = 0
const chunks = []
while(true) {
const {done, value} = await reader.read()
if(done) break
chunks.push(value)
receivedLength += value.length
console.log(`Received ${receivedLength} of ${contentLength}`)
}
const blob = new Blob(chunks)
const downloadUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = downloadUrl
a.download = fileName
a.click()
}
以上方法覆盖了 Vue 项目中常见的文件下载场景,可以根据具体需求选择合适的方式实现。






