axios.get() 方法用于发送 GET 请求至后端接口,并将响应数据的 responseType 设置为 ‘blob’,以便正确处理二进制文件。通过 window.URL.createObjectURL() 创建一个临时的下载链接,并使用 元素进行下载操作。然后,通过解析响应头中的 Content-Disposition 头部信息获取文件名,并将链接设置为下载属性。
// 在 Vue 组件中定义一个方法,用于触发下载
methods: {
downloadFile() {
// 调用后端接口获取文件路径或者内容
// 假设后端接口返回一个文件下载链接
axios.get('/api/download', { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
// 提取文件名
const contentDispositionHeader = response.headers['content-disposition'];
let fileName = 'file';
if (contentDispositionHeader) {
const fileNameMatch = contentDispositionHeader.match(/filename="(.+)"/);
if (fileNameMatch.length >= 2) {
fileName = fileNameMatch[1];
}
}
// 设置下载文件的属性(名称和类型)
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
// 清理创建的临时链接
URL.revokeObjectURL(url);
})
.catch(error => {
console.error(error);
// 处理错误
});
}
}
使用{responseType: ‘arraybuffer’}也可以正常下载