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

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue 实现闪烁

vue 实现闪烁

Vue 实现闪烁效果的方法 方法一:使用 CSS 动画 在 Vue 组件中定义一个闪烁的 CSS 动画,通过绑定 class 或 style 来控制元素的闪烁效果。 <template&…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现getapp

vue实现getapp

Vue 中实现全局获取应用实例的方法 在 Vue 3 中,可以通过 getCurrentInstance 方法获取当前组件实例,但需要明确其使用场景和限制。以下是具体实现方式: 方法一:通过 ge…

vue实现123456

vue实现123456

Vue 实现数字 123456 的显示 在 Vue 中显示数字 123456 非常简单,可以通过以下方法实现: 方法一:直接在模板中显示 <template> <div>…

vue实现伸缩

vue实现伸缩

Vue实现伸缩功能的方法 使用CSS过渡和Vue的v-if或v-show 通过CSS的transition属性结合Vue的条件渲染指令(v-if或v-show)可以实现元素的伸缩效果。定义一个CSS类…