vue实现header下载
Vue 实现文件下载的 Header 配置
在 Vue 中实现文件下载时,通常需要设置正确的 HTTP 头部(Header)以确保浏览器正确处理文件。以下是几种常见方法:

通过 axios 设置响应类型
使用 axios 发起请求时,设置 responseType 为 'blob',并处理返回的二进制数据:

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;
link.setAttribute('download', 'filename.ext');
document.body.appendChild(link);
link.click();
link.remove();
});
服务端设置 Content-Disposition
确保服务端返回以下头部:
Content-Type: application/octet-streamContent-Disposition: attachment; filename="filename.ext"
使用 Fetch API 实现
fetch('/api/download')
.then(res => res.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'filename.ext';
document.body.appendChild(a);
a.click();
a.remove();
});
处理大文件下载
对于大文件,可以显示下载进度:
axios.get('/api/download', {
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(`Download progress: ${percent}%`);
}
}).then(response => {
// 处理下载
});
注意事项
- 跨域请求需确保服务端设置了
Access-Control-Allow-Origin - 某些浏览器可能需要用户交互才能触发下载
- 文件名最好进行编码处理,避免特殊字符问题






