当前位置:首页 > VUE

vue中实现文件下载

2026-02-21 02:20:08VUE

使用 <a> 标签实现下载

在 Vue 中可以通过动态创建 <a> 标签实现文件下载。这种方法适用于已知文件 URL 的情况。

<template>
  <button @click="downloadFile">下载文件</button>
</template>

<script>
export default {
  methods: {
    downloadFile() {
      const link = document.createElement('a')
      link.href = 'https://example.com/path/to/file.pdf'
      link.download = 'filename.pdf'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
}
</script>

使用 Blob 对象下载

当需要从 API 获取文件数据时,可以使用 Blob 对象实现下载。

<script>
export default {
  methods: {
    async downloadFile() {
      try {
        const response = await fetch('https://api.example.com/download')
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)

        const link = document.createElement('a')
        link.href = url
        link.download = 'file.pdf'
        document.body.appendChild(link)
        link.click()

        window.URL.revokeObjectURL(url)
        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
      }
    }
  }
}
</script>

使用 axios 下载文件

使用 axios 库处理文件下载时,需要设置 responseType: 'blob'

import axios from 'axios'

export default {
  methods: {
    async downloadFile() {
      try {
        const response = await axios.get('https://api.example.com/download', {
          responseType: 'blob'
        })

        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.download = 'document.pdf'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
      }
    }
  }
}

处理大文件下载

对于大文件下载,可以显示下载进度。

methods: {
  async downloadLargeFile() {
    try {
      const response = await axios.get('https://example.com/large-file', {
        responseType: 'blob',
        onDownloadProgress: progressEvent => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          console.log(`下载进度: ${percentCompleted}%`)
        }
      })

      // 其余下载逻辑与之前相同
    } catch (error) {
      console.error('下载失败:', error)
    }
  }
}

处理后端返回的文件流

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

async downloadStream() {
  try {
    const response = await axios.get('https://api.example.com/stream', {
      responseType: 'blob'
    })

    // 从响应头获取文件名
    const contentDisposition = response.headers['content-disposition']
    let fileName = 'default.pdf'
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/)
      if (fileNameMatch.length > 1) {
        fileName = fileNameMatch[1]
      }
    }

    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载失败:', error)
  }
}

注意事项

确保服务器正确设置了 CORS 头部,否则跨域请求可能失败。对于需要认证的请求,需要在请求头中添加认证信息。

vue中实现文件下载

axios.get('https://api.example.com/protected-file', {
  responseType: 'blob',
  headers: {
    'Authorization': `Bearer ${token}`
  }
})

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

相关文章

vue实现倒计时抢券

vue实现倒计时抢券

Vue 实现倒计时抢券功能 核心逻辑 倒计时抢券功能需要结合时间计算、状态管理和界面交互。通过 Vue 的响应式特性和生命周期钩子,可以高效实现这一需求。 实现步骤 1. 数据准备 在 Vue 组件…

vue实现闪烁

vue实现闪烁

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

vue实现jqueryui

vue实现jqueryui

Vue 实现 jQuery UI 功能 在 Vue 项目中实现类似 jQuery UI 的功能,可以通过原生 Vue 组件或第三方库来实现。以下是几种常见 jQuery UI 功能的 Vue 替代方案…

vue插槽实现

vue插槽实现

插槽的基本概念 Vue插槽(Slot)是一种内容分发机制,允许父组件向子组件传递模板片段,子组件通过<slot>标签定义接收位置。插槽的核心作用是增强组件的灵活性和复用性。 默认插槽 子…

vue 实现拖拉

vue 实现拖拉

Vue 实现拖拽功能的方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

vue nexttick 实现

vue nexttick 实现

Vue nextTick 实现原理 Vue 的 nextTick 是一个用于在下次 DOM 更新循环结束之后执行延迟回调的方法。它主要用于确保在 DOM 更新完成后执行某些操作。 核心实现机制 ne…