当前位置:首页 > 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 头部,否则跨域请求可能失败。对于需要认证的请求,需要在请求头中添加认证信息。

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

vue中实现文件下载

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

相关文章

vue实现用户信息表

vue实现用户信息表

Vue 实现用户信息表的方法 使用 Vue CLI 创建项目 安装 Vue CLI 并初始化项目: npm install -g @vue/cli vue create user-info-tabl…

ssh vue 实现

ssh vue 实现

使用SSH连接Vue项目部署的服务器 在Vue项目开发或部署过程中,可能需要通过SSH连接到远程服务器进行配置或维护。以下是实现SSH连接并部署Vue项目的关键步骤: 生成SSH密钥对 在本地终端…

vue实现route

vue实现route

Vue 路由实现方法 Vue 中实现路由通常使用 vue-router 库,这是 Vue 官方推荐的路由管理器。以下是具体实现步骤: 安装 vue-router 通过 npm 或 yarn 安…

vue 实现打印

vue 实现打印

Vue 实现打印功能的方法 在Vue项目中实现打印功能,可以通过以下几种方式实现: 使用window.print()方法 通过调用浏览器的原生打印API实现基础打印功能,适用于简单内容打印。…

vue实现水印

vue实现水印

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

vue 实现视频

vue 实现视频

Vue 实现视频播放功能 使用 Vue 实现视频播放功能可以通过 HTML5 的 <video> 标签或第三方库(如 video.js)来实现。以下是两种常见的方法: 使用 HTML5…