当前位置:首页 > 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

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

vue实现文件下载demo

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 实现下载进度显示。

vue实现文件下载demo

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 的下载请求,需要在请求头中添加认证信息。

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

注意事项

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

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

相关文章

vue实现微博印象

vue实现微博印象

实现微博印象功能的核心思路 微博印象功能通常指用户发布微博后,系统自动分析文本内容并提取关键词或标签,以可视化形式展示。Vue实现该功能需要结合文本分析、关键词提取和前端渲染技术。 文本分析与关键词…

vue实现闪烁

vue实现闪烁

Vue实现元素闪烁效果 使用CSS动画实现 通过Vue绑定class结合CSS动画实现闪烁效果,代码简洁且性能较好。 <template> <div :class="{…

vue实现tag

vue实现tag

Vue 实现标签(Tag)功能 在 Vue 中实现标签(Tag)功能可以通过多种方式完成,以下是一些常见的方法和实现步骤: 使用动态组件和 v-for 通过 v-for 指令动态渲染标签列表,结合样…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue 实现轮播

vue 实现轮播

Vue 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template>…

vue实现必填

vue实现必填

Vue 实现表单必填验证的方法 在Vue中实现表单必填验证可以通过多种方式完成,以下是几种常见的方法: 使用HTML5原生属性 最简单的必填验证可以通过HTML5的required属性实现: &l…