vue axios实现文件下载
使用 Axios 实现文件下载
在 Vue 项目中,可以通过 Axios 发送请求实现文件下载功能。以下是具体实现方法:
发送 GET 请求下载文件
axios({
method: 'get',
url: '/api/download',
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'filename.ext')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
发送 POST 请求下载文件
axios({
method: 'post',
url: '/api/download',
data: { id: 123 },
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'filename.ext')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
处理后端返回的文件名
如果后端在响应头中返回文件名,可以这样处理:
axios({
method: 'get',
url: '/api/download',
responseType: 'blob'
}).then(response => {
const contentDisposition = response.headers['content-disposition']
let filename = 'default.ext'
if (contentDisposition) {
const match = contentDisposition.match(/filename="?(.+)"?/)
if (match && match[1]) {
filename = match[1]
}
}
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
封装为可复用方法
可以将文件下载功能封装为可复用的方法:
// utils/download.js
export function downloadFile(url, params = {}, method = 'get', filename = '') {
return axios({
method,
url,
data: method === 'post' ? params : null,
params: method === 'get' ? params : null,
responseType: 'blob'
}).then(response => {
const contentDisposition = response.headers['content-disposition']
let finalFilename = filename
if (!finalFilename && contentDisposition) {
const match = contentDisposition.match(/filename="?(.+)"?/)
if (match && match[1]) {
finalFilename = match[1]
}
}
const blobUrl = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = blobUrl
link.setAttribute('download', finalFilename || 'file')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(blobUrl)
})
}
在组件中使用
import { downloadFile } from '@/utils/download'
// 调用示例
downloadFile('/api/download', { id: 123 }, 'get', 'custom-filename.ext')
注意事项
- 确保后端接口正确设置了响应头
Content-Disposition - 对于大文件下载,可以考虑添加进度提示
- 在下载完成后调用
window.URL.revokeObjectURL()释放内存 - 某些浏览器可能需要用户交互才能触发下载







