当前位置:首页 > 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 实现计时功能 在 Vue 中实现计时功能可以通过多种方式完成,以下是几种常见的方法: 使用 setInterval 实现基础计时器 通过 setInterval 和 clearInterva…

vue实现高亮

vue实现高亮

Vue 实现文本高亮的方法 在 Vue 中实现文本高亮可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-html 指令 通过 v-html 指令可以动态插入 HTML 内容,将需要高…

vue实现granfana

vue实现granfana

Vue 实现类似 Grafana 的仪表盘 要在 Vue 中实现类似 Grafana 的仪表盘功能,需要结合数据可视化库、状态管理和 UI 组件。以下是关键步骤和推荐工具: 数据可视化库 使用 E…

vue实现拍照

vue实现拍照

Vue实现拍照功能 在Vue中实现拍照功能通常需要结合浏览器的MediaDevices API和Canvas元素。以下是具体实现方法: 安装依赖(可选) 如果需要更简单的封装,可以安装vue-web…

vue observer实现

vue observer实现

Vue Observer 实现原理 Vue 的响应式系统核心是通过 Object.defineProperty(Vue 2)或 Proxy(Vue 3)实现的 Observer 模式。以下是关键实现细…

vue拖拽实现

vue拖拽实现

Vue 拖拽实现方法 使用 HTML5 原生拖拽 API HTML5 提供了原生拖拽 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 drop 事…