当前位置:首页 > 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 的双向数据绑定主要通过 v-model 指令实现,其核心是结合了数据劫持(Object.defineProperty 或 Proxy)和发布-订阅模式。 数…

vue实现文档导入

vue实现文档导入

Vue 实现文档导入的方法 在 Vue 中实现文档导入功能通常涉及文件上传、解析和处理。以下是几种常见的方法: 使用原生文件输入和 FileReader 通过 HTML 的原生 <input…

vue伪函数实现

vue伪函数实现

Vue 伪函数实现方法 伪函数(Mock Function)在 Vue 中常用于测试或模拟某些逻辑,以下是几种常见的实现方式: 使用 Jest 的 jest.fn() 在单元测试中,可以通过 Je…

拖拽式编程vue实现

拖拽式编程vue实现

拖拽式编程在 Vue 中的实现方法 使用 HTML5 原生拖放 API Vue 可以结合 HTML5 的拖放 API 实现基础拖拽功能。通过 draggable 属性标记可拖拽元素,监听 dragst…

vue怎么实现数据检测

vue怎么实现数据检测

Vue 数据检测的实现方式 Vue 通过响应式系统实现数据检测,核心机制基于 Object.defineProperty(Vue 2)或 Proxy(Vue 3)。以下是具体实现方法: 基于 Vue…

vue设计与实现目录

vue设计与实现目录

以下是《Vue设计与实现》一书的典型目录结构(根据常见技术书籍及Vue核心内容整理): 响应式系统 响应式数据的基本原理 依赖收集与触发更新 实现简易响应式系统 Proxy与Refle…