当前位置:首页 > VUE

vue文件下载实现

2026-01-15 08:35:09VUE

使用 Blob 对象下载文件

在 Vue 中可以通过创建 Blob 对象实现文件下载。通过将后端返回的二进制数据转换为 Blob,再生成下载链接触发浏览器下载行为。

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.setAttribute('download', 'filename.ext')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
})

使用 FileSaver.js 库

FileSaver.js 提供了更简单的文件保存接口,适用于大多数现代浏览器。安装后可直接调用 saveAs 方法。

vue文件下载实现

npm install file-saver
import { saveAs } from 'file-saver'

axios.get('/api/download', { responseType: 'blob' }).then(response => {
  saveAs(response.data, 'filename.ext')
})

处理大文件分片下载

对于大文件下载,可以实现分片下载功能。通过设置 Range 请求头获取文件片段,最后合并所有片段。

vue文件下载实现

async function downloadLargeFile(url, filename) {
  const chunkSize = 1024 * 1024 // 1MB
  let startByte = 0
  let chunks = []

  while(true) {
    const endByte = startByte + chunkSize - 1
    const response = await axios.get(url, {
      responseType: 'blob',
      headers: { 'Range': `bytes=${startByte}-${endByte}` }
    })

    if(response.status === 206) {
      chunks.push(await response.data.arrayBuffer())
      startByte += chunkSize
    } else {
      break
    }
  }

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

前端生成文件下载

对于需要在前端生成文件内容再下载的场景,可以直接创建数据 URL 实现下载。

function downloadText(content, filename) {
  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}

处理下载进度显示

通过 axios 的 onDownloadProgress 配置可以获取下载进度,适用于需要显示进度条的场合。

axios.get('/api/download', {
  responseType: 'blob',
  onDownloadProgress: progressEvent => {
    const percent = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    )
    console.log(`下载进度: ${percent}%`)
  }
}).then(response => {
  saveAs(response.data, 'file.ext')
})

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

相关文章

vue实现前端注册

vue实现前端注册

Vue 实现前端注册功能 注册表单设计 使用 Vue 的模板语法创建注册表单,包含用户名、邮箱、密码和确认密码字段。表单需绑定 v-model 实现双向数据绑定。 <template>…

在线脑图 vue 实现

在线脑图 vue 实现

在线脑图 Vue 实现方案 使用开源库实现 推荐使用 mind-elixir 或 jsmind 这类开源库,它们专为脑图设计且支持 Vue 集成。 安装依赖: npm install mi…

vue实现文件模板展示

vue实现文件模板展示

Vue 实现文件模板展示的方法 在 Vue 中实现文件模板展示功能,可以通过多种方式完成。以下是几种常见的实现方法: 使用动态组件 动态组件允许根据条件切换不同的模板组件。通过 :is 属性绑定组…

vue实现无线滚动列表

vue实现无线滚动列表

无限滚动列表的实现方法 在Vue中实现无限滚动列表通常结合监听滚动事件和动态加载数据。以下是几种常见方法: 使用自定义指令 创建自定义指令v-infinite-scroll监听滚动事件: Vu…

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:用…

vue 实现在线预览

vue 实现在线预览

Vue 实现在线预览的常见方法 使用 iframe 嵌入 通过 iframe 标签可以嵌入多种类型的文件,如 PDF、图片、网页等。需要确保文件地址可访问。 <template>…