当前位置:首页 > VUE

vue实现文件下载

2026-01-11 20:37:20VUE

使用 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>

vue实现文件下载

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

相关文章

vue实现表格

vue实现表格

Vue 实现表格的方法 在 Vue 中实现表格可以通过多种方式完成,以下是几种常见的方法: 使用原生 HTML 表格 Vue 可以直接渲染原生 HTML 表格,通过 v-for 动态生成表格行和列。…

vue如何实现注册

vue如何实现注册

实现用户注册功能 在Vue中实现注册功能通常需要结合前端表单和后端API交互。以下是完整的实现方案: 创建注册表单组件 注册表单需要包含用户名、邮箱、密码等基本字段,并进行表单验证: <te…

vue的动画实现

vue的动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要通过内置组件和第三方库支持。 使用 Vue 内置过渡组件 Vue 的 transition 和 transition-group 组件…

vue单页面实现登录

vue单页面实现登录

实现登录功能的基本流程 在Vue单页面应用中实现登录功能,通常需要以下几个关键步骤: 创建登录表单组件 使用Vue的模板语法创建包含用户名和密码输入框的表单,并绑定数据到组件的data属性。 <…

vue实现选择本地文件

vue实现选择本地文件

实现文件选择功能 在Vue中实现本地文件选择可以通过HTML原生的<input type="file">元素实现。创建一个基本的文件选择组件: <template> &…

vue实现文件模板展示

vue实现文件模板展示

Vue 实现文件模板展示的方法 在 Vue 中实现文件模板展示功能,可以通过多种方式完成。以下是几种常见的实现方法: 使用动态组件 动态组件允许根据条件切换不同的模板组件。通过 :is 属性绑…