vue axios实现文件下载
使用 Axios 实现文件下载
在 Vue 项目中,可以通过 Axios 发送请求实现文件下载功能。以下是具体实现方法:
安装 Axios 确保项目中已安装 Axios,若未安装可通过以下命令安装:
npm install axios
导入 Axios 在需要使用的组件或文件中导入 Axios:
import axios from 'axios';
发送下载请求 通过 Axios 发送 GET 请求获取文件,并处理响应数据:
downloadFile() {
axios({
url: '/api/download', // 替换为实际文件下载接口
method: 'GET',
responseType: 'blob', // 必须指定响应类型为 blob
}).then(response => {
// 创建下载链接
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
// 从响应头获取文件名,或自定义文件名
const fileName = response.headers['content-disposition']
? response.headers['content-disposition'].split('filename=')[1]
: 'downloaded-file.pdf';
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
// 清理资源
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}).catch(error => {
console.error('下载失败:', error);
});
}
处理后端响应 后端接口需设置正确的响应头以支持文件下载:
Content-Type: 根据文件类型设置(如application/octet-stream)Content-Disposition: 包含文件名(如attachment; filename="example.pdf")
封装为可复用方法 可将下载逻辑封装为全局方法或工具函数:
// utils/download.js
export function downloadFile(url, fileName) {
axios({
url,
method: 'GET',
responseType: 'blob',
}).then(/* 同上处理逻辑 */);
}
注意事项
- 跨域请求需确保后端配置 CORS 允许相关头信息(如
Content-Disposition) - 大文件下载建议显示进度条,可通过 Axios 的
onDownloadProgress实现 - 错误处理应包含网络错误和业务错误(如权限不足)
带参数下载示例 若需传递查询参数:
axios({
url: '/api/download',
method: 'GET',
params: { id: 123 }, // 查询参数
responseType: 'blob',
});
POST 请求下载 某些接口可能需要 POST 方式:
axios({
url: '/api/download',
method: 'POST',
data: { id: 123 }, // 请求体
responseType: 'blob',
});
以上方法适用于 PDF、Excel、图片等各类文件下载场景,实际使用时需根据项目需求调整细节。







