当前位置:首页 > VUE

vue 实现附件下载

2026-02-19 08:59:19VUE

实现附件下载的基本方法

在Vue中实现附件下载通常通过前端生成下载链接或调用后端API完成。以下是几种常见实现方式:

使用<a>标签直接下载

对于静态文件或已知URL的资源,可直接使用HTML的<a>标签:

<template>
  <a href="/path/to/file.pdf" download="filename.pdf">下载文件</a>
</template>

download属性指定保存时的默认文件名。

通过Blob对象实现动态下载

当需要从API获取文件数据时,可使用Blob对象:

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()
    link.remove()
    window.URL.revokeObjectURL(url)
  })

处理后端返回的文件流

对于后端返回的文件流,需要正确设置响应类型:

async function downloadFile() {
  try {
    const res = await axios({
      method: 'get',
      url: '/api/file',
      responseType: 'blob'
    })
    const blob = new Blob([res.data])
    const downloadUrl = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = downloadUrl
    a.download = 'document.pdf'
    document.body.appendChild(a)
    a.click()
    URL.revokeObjectURL(downloadUrl)
    a.remove()
  } catch (error) {
    console.error('下载失败:', error)
  }
}

处理权限验证

需要验证权限时,可在请求头中添加token:

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

显示下载进度

对于大文件下载,可添加进度提示:

axios.get('/api/large-file', {
  responseType: 'blob',
  onDownloadProgress: progressEvent => {
    const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
    console.log(`下载进度: ${percent}%`)
  }
})

处理不同文件类型

根据文件类型设置正确的MIME类型:

const fileType = 'application/pdf'
const blob = new Blob([response.data], { type: fileType })

错误处理

添加适当的错误处理逻辑:

axios.get('/api/download')
  .catch(error => {
    if (error.response.status === 404) {
      alert('文件不存在')
    } else {
      alert('下载失败')
    }
  })

封装为可复用组件

可将下载逻辑封装为可复用组件:

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

<script>
export default {
  methods: {
    async downloadFile() {
      // 实现下载逻辑
    }
  }
}
</script>

vue  实现附件下载

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

相关文章

vue实现store

vue实现store

Vue 实现 Store 在 Vue 中,可以通过 Vuex 或 Pinia 实现全局状态管理(Store)。以下是两种主流方案的实现方法。 使用 Vuex 实现 Store Vuex 是 Vue…

vue  select实现

vue select实现

Vue Select 实现方法 在 Vue 中实现下拉选择功能可以使用原生 <select> 标签或第三方库如 vue-select。以下是两种方法的详细说明: 原生 HTML Sel…

实现vue模版

实现vue模版

Vue 模板的基本结构 Vue 模板基于 HTML 语法,通过 Vue 的指令和插值实现动态渲染。以下是一个基础模板示例: <template> <div id="…

vue实现拖放

vue实现拖放

Vue 实现拖放功能 Vue 中实现拖放功能通常可以通过 HTML5 的原生拖放 API 或第三方库(如 vuedraggable)来实现。以下是两种方法的详细说明。 使用 HTML5 原生拖放 A…

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defau…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…