当前位置:首页 > VUE

vue实现文件下载demo

2026-02-24 21:06:12VUE

Vue 实现文件下载的几种方法

通过 <a> 标签下载

在 Vue 模板中使用 <a> 标签的 download 属性实现文件下载。适用于已知文件 URL 且无需鉴权的场景。

<template>
  <a :href="fileUrl" download="filename.pdf">点击下载文件</a>
</template>

<script>
export default {
  data() {
    return {
      fileUrl: 'https://example.com/files/sample.pdf'
    }
  }
}
</script>

使用 Blob 对象和 URL.createObjectURL

适用于需要从后端获取二进制流或需要处理动态生成文件的场景。

methods: {
  downloadFile() {
    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', 'file.pdf')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      })
  }
}

处理大文件下载(带进度条)

结合 axios 的 onDownloadProgress 实现下载进度显示。

methods: {
  downloadWithProgress() {
    axios({
      url: '/api/large-file',
      method: 'GET',
      responseType: 'blob',
      onDownloadProgress: progressEvent => {
        const percent = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        )
        console.log(`下载进度: ${percent}%`)
      }
    }).then(response => {
      // 处理文件下载逻辑
    })
  }
}

后端返回文件流时的处理

当后端返回文件流时,需要正确设置响应头和处理响应数据。

axios.get('/api/export-excel', {
  responseType: 'arraybuffer'
}).then(res => {
  const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'report.xlsx'
  a.click()
})

处理需要鉴权的文件下载

对于需要携带 token 的下载请求,需要在请求头中添加认证信息。

vue实现文件下载demo

axios.get('/api/protected-file', {
  headers: {
    'Authorization': `Bearer ${localStorage.getItem('token')}`
  },
  responseType: 'blob'
}).then(res => {
  // 处理下载逻辑
})

注意事项

  • 跨域问题需要后端配合设置 CORS 响应头
  • 大文件下载建议分块处理或使用断点续传
  • 移动端可能需要特殊处理某些浏览器的兼容性问题
  • 下载完成后及时释放创建的 Object URL 避免内存泄漏

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

相关文章

vue 实现excel

vue 实现excel

Vue 实现 Excel 功能 前端导出 Excel 使用 xlsx 库可以轻松实现前端 Excel 导出功能。安装依赖: npm install xlsx 导出 Excel 示例代码: impo…

vue实现京东

vue实现京东

Vue 实现京东电商网站的关键步骤 项目搭建与基础配置 使用 Vue CLI 或 Vite 初始化项目,安装 Vue Router 管理路由,Vuex/Pinia 管理状态。配置基础 UI 框架如 E…

vue实现字幕

vue实现字幕

Vue 实现字幕功能 在 Vue 中实现字幕功能可以通过动态绑定数据和 CSS 动画来实现。以下是具体实现方法: 1. 基础字幕组件 创建一个字幕组件,通过 v-model 或 props 接收字…

vue实现修改

vue实现修改

Vue 实现修改功能的方法 在 Vue 中实现修改功能通常涉及表单绑定、状态管理和 API 调用。以下是几种常见实现方式: 双向数据绑定实现表单修改 使用 v-model 指令绑定表单元素与组件数据…

vue如何实现mvvm

vue如何实现mvvm

Vue 实现 MVVM 的核心机制 Vue 的 MVVM(Model-View-ViewModel)实现依赖于数据绑定和响应式系统,通过以下核心机制完成: 数据劫持(响应式系统) Vue 使用 Ob…

vue实现选择框

vue实现选择框

Vue 实现选择框的方法 Vue 中可以通过多种方式实现选择框(下拉框),包括原生 HTML 的 <select> 元素结合 Vue 的数据绑定,或者使用第三方 UI 库如 Element…