当前位置:首页 > VUE

vue前端实现文件下载

2026-02-20 22:07:39VUE

使用 Blob 对象和 URL.createObjectURL

通过创建 Blob 对象并生成临时 URL 实现文件下载。适用于后端返回文件流或前端生成文件的场景。

// 假设 response 是后端返回的文件流
const blob = new Blob([response.data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'filename.ext'; // 设置下载文件名
link.click();
window.URL.revokeObjectURL(url); // 释放内存

直接使用 a 标签下载

适用于已知文件 URL 且服务器允许直接下载的情况。

<a href="/path/to/file.ext" download="custom-filename.ext">下载文件</a>

处理跨域文件下载

当文件位于不同域名时,可能需要后端配合设置 CORS 或通过代理下载。

axios.get('/api/download', {
  responseType: 'blob',
  headers: {
    'Authorization': 'Bearer your_token'
  }
}).then(response => {
  const contentDisposition = response.headers['content-disposition'];
  const filename = contentDisposition.split('filename=')[1];
  const blob = new Blob([response.data]);
  // 后续步骤同第一种方法
});

大文件分片下载

对于大文件下载,可以显示下载进度并支持暂停续传。

const downloadFile = async (url, fileName) => {
  const response = await fetch(url);
  const reader = response.body.getReader();
  const contentLength = +response.headers.get('Content-Length');
  let receivedLength = 0;
  const chunks = [];

  while(true) {
    const {done, value} = await reader.read();
    if(done) break;
    chunks.push(value);
    receivedLength += value.length;
    console.log(`下载进度: ${(receivedLength/contentLength*100).toFixed(2)}%`);
  }

  const blob = new Blob(chunks);
  // 后续下载步骤
};

前端生成文件并下载

适用于需要在前端动态生成文件内容的场景。

const content = '文件内容';
const blob = new Blob([content], {type: 'text/plain'});
// 后续下载步骤同第一种方法

注意事项

  • 确保服务器正确设置了 Content-Disposition 响应头
  • 处理可能的错误情况,如网络中断或权限问题
  • 移动端可能需要特殊处理,某些浏览器对下载限制较多
  • 考虑添加下载进度提示和完成通知
  • 对于敏感文件,应通过授权验证后再允许下载

vue前端实现文件下载

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

相关文章

vue实现冰墩墩

vue实现冰墩墩

使用 Vue 实现冰墩墩动画 通过 Vue 的动画特性和 SVG 技术,可以动态渲染冰墩墩的形象。以下是具体实现方法: 准备 SVG 素材 冰墩墩的形象通常由多个 SVG 路径组成,包括身体轮廓、面…

vue实现关键词轮播

vue实现关键词轮播

Vue 实现关键词轮播 基础实现方案 使用 Vue 的 v-for 和 setInterval 实现基础轮播效果: <template> <div class="keyword…

vue原型实现

vue原型实现

Vue 原型实现的关键点 Vue.js 的原型系统是其响应式机制的核心部分,通过原型链实现数据的动态绑定和依赖收集。以下是实现 Vue 原型的主要技术要点。 数据响应式原理 Vue 通过 Objec…

vue实现cs

vue实现cs

Vue 实现 CS(Client-Side)渲染的常见方法 Vue.js 是一个用于构建用户界面的渐进式框架,默认采用客户端渲染(CSR)。以下是几种常见的实现方式: 使用 Vue CLI 创建项目…

vue实现单据

vue实现单据

Vue 实现单据功能的方法 使用 Vue 实现单据功能通常涉及表单设计、数据绑定、验证和提交等环节。以下是具体实现方案: 表单设计与数据绑定 使用 Vue 的 v-model 指令实现表单数据的双向…

vue实现toggle

vue实现toggle

Vue 实现 Toggle 功能 在 Vue 中实现 toggle(切换)功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 和 v-on 通过 v-model 绑定数据,结合…