当前位置:首页 > VUE

vue实现文档下载

2026-02-19 09:37:56VUE

使用 <a> 标签下载

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

// 方法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。

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使用vr实现标注

vue使用vr实现标注

Vue 中使用 VR 实现标注的方法 在 Vue 项目中结合 VR 技术实现标注功能,可以通过 WebXR 和 Three.js 等库实现。以下为具体实现方法: 安装依赖 确保项目中已安装 Thre…

vue聊天实现

vue聊天实现

Vue 聊天应用实现步骤 创建 Vue 项目 使用 Vue CLI 或 Vite 初始化项目,安装必要依赖(如 Vue 3、Element UI 或 Vuetify 用于 UI 组件)。 npm…

vue实现markdown

vue实现markdown

Vue 实现 Markdown 编辑器 在 Vue 中实现 Markdown 编辑器可以通过集成第三方库或自定义解析器完成。以下是两种常见方法: 使用第三方库(如 marked 或 markdow…

vue 实现回复

vue 实现回复

Vue 实现回复功能 在 Vue 中实现回复功能通常涉及表单提交、数据绑定和列表渲染。以下是实现步骤和代码示例: 数据绑定与表单 <template> <div>…

javascript实现vue

javascript实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,主要包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化的实现示例。 数据响应式系统 通过 Object.d…

vue实现getapp

vue实现getapp

Vue 中实现全局获取应用实例的方法 在 Vue 3 中,可以通过 getCurrentInstance 方法获取当前组件实例,但需要明确其使用场景和限制。以下是具体实现方式: 方法一:通过 ge…