当前位置:首页 > 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 实现下载。

vue实现文件下载

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 回调。

vue实现文件下载

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 table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…

vue 实现工具

vue 实现工具

Vue 实现工具的方法 使用 Vue 实现工具功能可以通过多种方式完成,具体取决于工具的类型和需求。以下是几种常见的方法: 组件化实现 创建一个独立的 Vue 组件来封装工具功能。例如,实现一个计…

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…

vue指令实现

vue指令实现

Vue 指令的实现方式 Vue 指令是特殊的标记,用于在 DOM 元素上应用特定的行为。可以通过全局或局部方式注册自定义指令。 全局注册指令 在 Vue 应用中通过 Vue.directive 方法…

vue实现秒表

vue实现秒表

实现秒表功能 在Vue中实现秒表功能需要处理时间显示、开始、暂停和重置逻辑。以下是具体实现方式: 基础实现代码 <template> <div> <div&…

vue实现打印

vue实现打印

使用Vue实现打印功能 在Vue项目中实现打印功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用window.print() 这种方法适用于打印整个页面或特定区域的内容。 // 在Vu…