当前位置:首页 > VUE

vue前端实现文件下载

2026-01-20 06:03:23VUE

使用 window.open 直接下载

通过 window.open 直接打开文件链接触发下载,适用于简单的文件下载场景。
将文件 URL 作为参数传入,浏览器会自动处理下载行为:

window.open('https://example.com/file.pdf', '_blank');

使用 <a> 标签动态触发下载

创建隐藏的 <a> 标签,设置 download 属性后模拟点击,适合需要自定义文件名的情况:

vue前端实现文件下载

const link = document.createElement('a');
link.href = 'https://example.com/file.pdf';
link.download = 'custom-filename.pdf'; // 指定下载文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

通过 Blob 对象下载二进制数据

当需要处理后端返回的二进制流(如 Axios 响应)时,可通过 Blob 转换并下载:

vue前端实现文件下载

axios.get('/api/download', { responseType: 'blob' }).then(response => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.download = 'file.zip';
  link.click();
  window.URL.revokeObjectURL(url); // 释放内存
});

处理大文件分片下载

对于大文件下载,可结合 Content-Range 实现分片下载与合并:

async function downloadLargeFile(url, fileName, chunkSize = 1024 * 1024) {
  let startByte = 0;
  const chunks = [];

  while (true) {
    const response = await fetch(url, {
      headers: { 'Range': `bytes=${startByte}-${startByte + chunkSize}` }
    });
    if (!response.ok) break;
    chunks.push(await response.blob());
    startByte += chunkSize;
  }

  const blob = new Blob(chunks);
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
}

添加下载进度提示

通过 Axios 的 onDownloadProgress 实现进度显示:

axios({
  url: '/api/download',
  method: 'GET',
  responseType: 'blob',
  onDownloadProgress: progressEvent => {
    const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
    console.log(`下载进度: ${percent}%`);
  }
}).then(response => {
  // 处理下载完成逻辑
});

注意事项

  • 跨域问题需确保服务器配置 Access-Control-Allow-Origin
  • 部分浏览器可能限制非用户触发的下载行为,建议在按钮点击事件中触发
  • 移动端需测试兼容性,部分浏览器对 download 属性支持有限

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

相关文章

vue实现点击页面切换

vue实现点击页面切换

实现点击页面切换功能 在Vue中实现点击页面切换功能,可以通过路由跳转或组件动态渲染两种方式完成。以下是具体实现方法: 使用Vue Router实现页面跳转 安装Vue Router后,在项目中配置…

vue实现drag

vue实现drag

Vue 实现拖拽功能的方法 在 Vue 中实现拖拽功能可以通过原生 HTML5 的拖拽 API 或第三方库如 vuedraggable 来完成。以下是两种常见方法的实现方式。 使用 HTML5 拖拽…

vue筛选实现

vue筛选实现

Vue 筛选实现方法 使用计算属性实现筛选 计算属性是 Vue 中实现数据筛选的常用方式。通过定义一个计算属性,可以根据输入的条件动态过滤数据。 <template> <div…

vue实现slidetoggle

vue实现slidetoggle

Vue 实现 SlideToggle 效果 SlideToggle 是一种常见的交互效果,元素以滑动方式展开或收起。以下是几种实现方法: 使用 CSS Transition 和 v-show 通过…

vue实现curd

vue实现curd

Vue实现CRUD操作 初始化Vue项目 使用Vue CLI创建新项目,安装必要依赖如axios用于HTTP请求 vue create crud-demo cd crud-demo npm inst…

vue实现白板

vue实现白板

Vue实现白板功能 使用Vue实现白板功能可以通过HTML5的Canvas API结合Vue的响应式特性来完成。以下是实现白板功能的关键步骤: 安装依赖 在Vue项目中安装必要的依赖,如vue-dr…