当前位置:首页 > 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 中实现页签功能通常涉及动态组件、路由或状态管理。以下是几种常见的实现方式: 使用动态组件 通过 Vue 的 <component> 动态组件结合 v-f…

vue实现表格多行修改

vue实现表格多行修改

实现多行编辑表格 在Vue中实现表格的多行编辑功能,可以通过以下方法完成。这里以Element UI的表格组件为例,但思路适用于其他UI库或原生实现。 数据准备 定义表格数据和编辑状态管理变量:…

vue轮询实现

vue轮询实现

Vue 轮询实现方法 在 Vue 中实现轮询可以通过以下几种方式: 使用 setInterval data() { return { pollInterval: null }…

vue实现github

vue实现github

Vue 实现 GitHub 相关功能 创建 GitHub API 请求 在 Vue 项目中,可以使用 axios 或 fetch 与 GitHub API 进行交互。需要在 GitHub 上创建个人访…

vue实现按钮

vue实现按钮

Vue 实现按钮的方法 使用原生 HTML 按钮 在 Vue 模板中可以直接使用 HTML 的 <button> 元素,通过 v-on 或 @ 绑定点击事件。 <template&…

vue实现回复

vue实现回复

Vue 实现回复功能 在 Vue 中实现回复功能通常涉及前端表单交互、数据绑定和后端通信。以下是实现回复功能的详细步骤: 数据绑定与表单设计 使用 Vue 的 v-model 绑定回复框的输入内容,…