vue实现文件下载
使用 Blob 对象和 URL.createObjectURL
通过创建 Blob 对象生成文件内容,利用 URL.createObjectURL 生成临时链接,再通过动态创建 <a> 标签触发下载。
function downloadFile(content, fileName, mimeType) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
直接请求服务器文件
适用于已有服务器文件路径的情况,通过动态创建 <a> 标签或 window.open 实现下载。
function downloadFromServer(fileUrl, fileName) {
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName || fileUrl.split('/').pop();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
使用 axios 处理文件流
当后端返回文件流时,通过设置 responseType 为 'blob' 获取数据,再转换为可下载的 URL。
axios({
method: 'get',
url: '/api/download',
responseType: 'blob'
}).then(response => {
const url = URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.download = 'filename.ext';
link.click();
URL.revokeObjectURL(url);
});
处理大文件分片下载
对于大文件下载可显示进度条,使用 axios 的 onDownloadProgress 回调。
axios({
method: 'get',
url: '/api/large-file',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log(percentCompleted);
}
}).then(response => {
// 处理下载逻辑
});
封装为 Vue 指令
将下载功能封装为可复用的 Vue 指令,方便全局调用。
Vue.directive('download', {
bind(el, binding) {
el.addEventListener('click', () => {
const { url, name } = binding.value;
const link = document.createElement('a');
link.href = url;
link.download = name || url.split('/').pop();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
});
使用方式:
<button v-download="{ url: '/file.pdf', name: 'document.pdf' }">
下载文件
</button>






