当前位置:首页 > VUE

vue文件下载实现

2026-03-08 11:15:20VUE

Vue 文件下载实现方法

使用 <a> 标签下载

通过动态创建 <a> 标签实现下载,适用于已知文件 URL 的场景:

const downloadFile = (url, filename) => {
  const link = document.createElement('a')
  link.href = url
  link.download = filename || 'file'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

通过 Blob 对象下载

适用于后端返回二进制流数据的场景:

axios.get('/api/download', { responseType: 'blob' }).then(res => {
  const blob = new Blob([res.data])
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'filename.ext'
  link.click()
  window.URL.revokeObjectURL(url)
})

使用 FileSaver.js 库

安装 FileSaver 简化下载流程:

vue文件下载实现

npm install file-saver

使用示例:

import { saveAs } from 'file-saver'

// 从URL下载
saveAs('https://example.com/file.pdf', 'custom-name.pdf')

// 从Blob下载
const blob = new Blob([data], { type: 'application/octet-stream' })
saveAs(blob, 'filename.ext')

处理大文件分片下载

对于大文件可采用分片下载:

vue文件下载实现

const downloadChunked = 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(`Downloaded ${receivedLength} of ${contentLength}`)
  }

  const blob = new Blob(chunks)
  saveAs(blob, filename)
}

添加下载进度提示

结合 axios 的 onDownloadProgress 实现进度显示:

axios.get('/large-file', {
  responseType: 'blob',
  onDownloadProgress: progressEvent => {
    const percent = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    )
    console.log(`Download: ${percent}%`)
  }
}).then(res => {
  // 处理下载完成逻辑
})

服务端配合要求

后端接口需要设置正确的响应头:

Content-Disposition: attachment; filename="example.pdf"
Content-Type: application/octet-stream

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

相关文章

vue弹幕实现不重叠

vue弹幕实现不重叠

实现 Vue 弹幕不重叠的方法 CSS 定位与动画控制 通过绝对定位和动态计算弹幕轨道高度,确保弹幕在不同轨道上运行。每条弹幕占据固定高度的轨道,避免重叠。 // 弹幕轨道高度计算 const tr…

vue实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="we…

vue实现popup

vue实现popup

Vue 实现 Popup 弹窗 使用 Vue 原生组件 创建一个基本的 Vue 组件作为弹窗,通过 v-if 或 v-show 控制显示隐藏。 <template> <div&…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单文…

vue 分页 实现

vue 分页 实现

Vue 分页实现方法 使用第三方库(如 Element UI) Element UI 提供了现成的分页组件 el-pagination,适合快速集成。 安装 Element UI: npm ins…

vue实现openoffice

vue实现openoffice

Vue 中集成 OpenOffice 的实现方法 在 Vue 项目中集成 OpenOffice 通常需要通过后端服务或现有库实现文档的预览和编辑功能。以下是几种常见的实现方式: 使用 OnlyOff…