当前位置:首页 > 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 且服务器允许直接下载的情况。

vue前端实现文件下载

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

处理跨域文件下载

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

vue前端实现文件下载

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 computed 实现

vue computed 实现

computed 的基本用法 在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。 new Vue({ data: {…

vue实现suspense

vue实现suspense

Vue 3 中实现 Suspense Suspense 是 Vue 3 引入的一个内置组件,用于处理异步依赖的加载状态。它允许在等待异步组件或异步数据加载时显示一个后备内容(fallback),直到异…

vue tab实现

vue tab实现

Vue Tab 实现方法 使用动态组件实现 Tab 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现 Ta…

vue 实现href

vue 实现href

Vue 实现 href 的方法 在 Vue 中实现 href 功能可以通过多种方式,具体取决于需求场景。以下是几种常见的方法: 使用 <a> 标签 直接使用 HTML 的 <a&g…

vue实现selectable

vue实现selectable

Vue 实现可选择的 Select 组件 在 Vue 中实现一个可选择的 Select 组件,可以通过以下几种方式: 使用原生 HTML select 元素 <template>…

vue 实现遮罩

vue 实现遮罩

Vue 实现遮罩层的方法 使用固定定位和透明背景 在Vue中实现遮罩层可以通过CSS固定定位结合透明背景色完成。创建一个全屏遮罩组件,利用position: fixed覆盖整个视窗。 <tem…