当前位置:首页 > 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);
    });
  }
});

使用方式:

vue实现文件下载

<button v-download="{ url: '/file.pdf', name: 'document.pdf' }">
  下载文件
</button>

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

相关文章

vue实现3d宇宙

vue实现3d宇宙

Vue实现3D宇宙效果 使用Three.js库 Three.js是一个强大的JavaScript 3D库,可以轻松集成到Vue项目中。安装Three.js依赖: npm install three…

vue实现日历

vue实现日历

Vue 实现日历的基本方法 使用 Vue 实现日历可以通过自定义组件或借助第三方库完成。以下是两种常见实现方式: 自定义日历组件 创建基于 Vue 的日历组件需要处理日期计算和渲染逻辑。核心是生成当…

vue 实现上传

vue 实现上传

Vue 实现文件上传 使用 Vue 实现文件上传可以通过原生 HTML 的 <input type="file"> 或第三方库(如 axios、vue-upload-component)完…

vue遮罩实现

vue遮罩实现

实现 Vue 遮罩的常见方法 使用 CSS 定位和透明度 创建一个全屏遮罩层,通过 CSS 固定定位覆盖整个视口,并设置半透明背景色。 <template> <div cl…

vue实现单词逆转

vue实现单词逆转

实现单词逆转的方法 在Vue中实现单词逆转可以通过多种方式完成,以下是几种常见的方法: 使用计算属性逆转单词 计算属性是Vue中处理数据逻辑的理想选择。可以通过计算属性来实现单词逆转: &…

vue 实现文字滚动

vue 实现文字滚动

Vue 实现文字滚动效果 使用CSS动画实现 通过CSS的@keyframes和transform属性实现文字滚动效果: <template> <div class="scro…