当前位置:首页 > VUE

vue实现文档下载

2026-02-19 09:37:56VUE

使用 <a> 标签下载

通过动态生成 <a> 标签并触发点击实现下载。适用于直接下载静态文件或后端返回的二进制流。

vue实现文档下载

// 方法1: 直接下载静态文件
const downloadByLink = (url, filename) => {
  const link = document.createElement('a')
  link.href = url
  link.download = filename || 'document'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 使用示例
downloadByLink('/files/report.pdf', '季度报告.pdf')

处理 Blob 数据下载

当后端返回二进制流(如 Blob 数据)时,需先转换为可下载的 URL。

vue实现文档下载

const downloadBlob = (blobData, fileName) => {
  const url = window.URL.createObjectURL(blobData)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  link.click()
  window.URL.revokeObjectURL(url) // 释放内存
}

// 结合axios示例
axios.get('/api/download', {
  responseType: 'blob'
}).then(res => {
  downloadBlob(res.data, 'export.xlsx')
})

文件流下载处理

针对后端返回文件流的情况,需设置正确的响应类型和响应头解析。

axios({
  method: 'get',
  url: '/api/export',
  responseType: 'blob',
}).then(response => {
  const contentDisposition = response.headers['content-disposition']
  const fileName = decodeURIComponent(
    contentDisposition.match(/filename=(.*?)(;|$)/)[1]
  )

  const blob = new Blob([response.data])
  const downloadUrl = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = downloadUrl
  a.download = fileName
  a.click()
  URL.revokeObjectURL(downloadUrl)
})

封装为 Vue 指令

可复用逻辑可封装为全局指令,通过 v-download 调用。

// main.js 全局注册
Vue.directive('download', {
  bind(el, binding) {
    el.addEventListener('click', () => {
      const { url, filename } = binding.value
      const link = document.createElement('a')
      link.href = url
      link.download = filename || 'download'
      link.click()
    })
  }
})

// 组件中使用
<button v-download="{ url: '/file.doc', filename: '合同.doc' }">
  下载文档
</button>

注意事项

  • 跨域问题需确保服务器配置 Access-Control-Allow-Origin
  • 大文件下载建议显示进度条,可通过 axiosonDownloadProgress 实现
  • 后端应设置正确的 Content-Disposition 响应头
  • 移动端部分浏览器可能限制自动下载,需用户主动触发

完整组件示例

<template>
  <div>
    <button @click="handleDownload">下载PDF</button>
    <button @click="handleExport">导出Excel</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleDownload() {
      this.$axios.get('/file.pdf', {
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data])
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = 'document.pdf'
        link.click()
      })
    },

    handleExport() {
      this.$axios.get('/api/export', {
        responseType: 'blob',
        onDownloadProgress: progressEvent => {
          const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          console.log(`下载进度: ${percent}%`)
        }
      }).then(res => {
        const fileName = res.headers['content-disposition']
          .split('filename=')[1]
          .replace(/"/g, '')

        const url = window.URL.createObjectURL(res.data)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    }
  }
}
</script>

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

相关文章

vue实现逻辑

vue实现逻辑

Vue 实现逻辑的核心概念 Vue.js 是一个渐进式 JavaScript 框架,其核心逻辑围绕数据驱动和组件化开发。通过响应式系统、虚拟 DOM 和组件生命周期等机制,Vue 实现了高效的前端开发…

vue实现水印

vue实现水印

Vue 实现水印的方法 使用 CSS 背景图 通过 CSS 的 background-image 和 background-repeat 属性实现水印效果。创建一个包含水印文本的 Canvas,将其转…

vue实现注册

vue实现注册

Vue 实现注册功能 注册功能通常涉及前端表单、数据验证、与后端 API 的交互等步骤。以下是一个完整的 Vue 实现注册功能的方案。 创建注册表单 使用 Vue 的模板语法创建注册表单,包含用户名…

vue 实现循环

vue 实现循环

Vue 实现循环的方法 在 Vue 中,可以使用 v-for 指令来实现循环渲染列表数据。以下是几种常见的循环实现方式: 基本数组循环 <template> <ul>…

vue实现例子

vue实现例子

以下是一些常见的 Vue 实现例子,涵盖基础功能到进阶应用场景: 基础数据绑定 使用 v-model 实现双向数据绑定: <template> <div> &l…

vue实现左右布局

vue实现左右布局

实现左右布局的方法 在Vue中实现左右布局可以通过多种方式完成,以下是几种常见的方法: 使用Flexbox布局 Flexbox是一种现代的CSS布局方式,可以轻松实现左右布局。 <t…