当前位置:首页 > VUE

vue实现文件下载

2026-02-09 09:17:57VUE

使用 <a> 标签下载文件

通过动态创建 <a> 标签实现文件下载,适用于已知文件 URL 的情况。
在 Vue 组件中定义方法,动态设置 hrefdownload 属性,触发点击事件。

methods: {
  downloadFile(url, fileName) {
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName || 'file';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

通过 Blob 对象下载动态内容

当需要下载后端返回的二进制流(如 Axios 响应)时,可将数据转换为 Blob 对象,生成临时 URL。

axios.get('/api/download', { responseType: 'blob' }).then(response => {
  const blob = new Blob([response.data]);
  const url = window.URL.createObjectURL(blob);
  this.downloadFile(url, 'example.pdf'); // 复用前例方法
  window.URL.revokeObjectURL(url); // 释放内存
});

处理后端文件名

若后端通过响应头返回文件名,可从 content-disposition 头中提取:

const contentDisposition = response.headers['content-disposition'];
const fileName = contentDisposition.split('filename=')[1].trim();

大文件分块下载

对于大文件,可采用流式处理避免内存问题,使用 fetchReadableStream

async function downloadLargeFile(url) {
  const response = await fetch(url);
  const reader = response.body.getReader();
  const chunks = [];

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
  }

  const blob = new Blob(chunks);
  const objectUrl = URL.createObjectURL(blob);
  this.downloadFile(objectUrl, 'large_file.zip');
}

进度显示实现

通过 Axios 的 onDownloadProgress 事件实现下载进度条:

vue实现文件下载

axios.get('/api/file', {
  responseType: 'blob',
  onDownloadProgress: progressEvent => {
    const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
    console.log(`下载进度: ${percent}%`);
  }
}).then(response => {
  // 处理下载完成逻辑
});

标签: 文件vue
分享给朋友:

相关文章

vue   实现单选

vue 实现单选

Vue 实现单选功能 在 Vue 中实现单选功能可以通过多种方式,以下是几种常见的方法: 使用原生 <input type="radio"> 绑定 v-model 通过 v-model…

vue能实现

vue能实现

Vue.js 是一个流行的前端框架,能够实现多种功能。以下是 Vue 能够实现的主要功能和特性: 响应式数据绑定 Vue 的核心特性之一是响应式数据绑定。通过数据驱动视图,当数据发生变化时,视图会自…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…

vue 实现树状

vue 实现树状

Vue 实现树状结构的方法 递归组件实现树状结构 递归组件是 Vue 中实现树状结构的常见方法。通过组件自身调用自身,可以轻松构建多层级树状结构。 <template> <ul…

vue实现mvvm

vue实现mvvm

Vue 实现 MVVM 模式 MVVM(Model-View-ViewModel)是一种前端架构模式,Vue 是其典型实现之一。MVVM 的核心是通过数据绑定和响应式系统实现视图与数据的自动同步。…

vue实现上划

vue实现上划

Vue 实现上划功能 在Vue中实现上划功能,可以通过监听触摸事件(touchstart、touchmove、touchend)来判断用户的手势方向。以下是实现上划功能的几种方法: 监听触摸事件 通…