当前位置:首页 > 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   实现单选

vue 实现单选

Vue 实现单选功能 在 Vue 中实现单选功能可以通过多种方式,以下是几种常见的方法: 使用原生 <input type="radio"> 绑定 v-model 通过 v-model…

vue实现标签

vue实现标签

Vue 实现标签的方法 在 Vue 中实现标签功能可以通过多种方式完成,以下是几种常见的方法: 使用动态组件 动态组件可以根据不同的条件渲染不同的标签内容。通过 :is 属性动态绑定组件名,实现标签…

vue  实现tab

vue 实现tab

实现 Tab 切换功能 在 Vue 中实现 Tab 切换功能可以通过动态组件或条件渲染完成。以下是两种常见方法: 使用 v-if 或 v-show 实现条件渲染 通过绑定 currentTab 变量…

vue实现抽屉

vue实现抽屉

Vue 实现抽屉组件 抽屉组件是一种常见的 UI 模式,通常用于从屏幕边缘滑出内容。以下是几种实现抽屉的方法: 使用 Vue 原生实现 创建一个基本的抽屉组件,利用 Vue 的过渡和条件渲染功能。…

mui实现vue

mui实现vue

mui 实现 Vue 的步骤 mui 是一个轻量级的前端框架,常用于移动端开发。结合 Vue 可以实现高效的开发体验。以下是具体实现方法。 安装 mui 和 Vue 通过 npm 或 yarn 安装…

vue 实现hover

vue 实现hover

Vue 实现 Hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 伪类 :hover 最简单的方式是直接使用 CSS 的 :hov…