当前位置:首页 > VUE

vue axios实现自动下载

2026-01-22 04:20:16VUE

Vue 中使用 Axios 实现自动下载

在 Vue 项目中,可以通过 Axios 发起请求获取文件数据,并结合 Blob 对象和 URL.createObjectURL 实现自动下载功能。以下是具体实现方法:

基本实现步骤

安装 Axios(如未安装):

npm install axios

在 Vue 组件中引入 Axios:

import axios from 'axios';

发起请求并处理文件下载:

axios({
  method: 'get',
  url: '文件下载地址',
  responseType: 'blob' // 必须指定响应类型为 blob
}).then(response => {
  // 创建 Blob 对象
  const blob = new Blob([response.data]);

  // 创建下载链接
  const downloadUrl = window.URL.createObjectURL(blob);

  // 创建隐藏的 <a> 标签触发下载
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.setAttribute('download', '文件名.扩展名'); // 设置下载文件名
  document.body.appendChild(link);
  link.click();

  // 清理对象 URL 和 DOM 元素
  window.URL.revokeObjectURL(downloadUrl);
  document.body.removeChild(link);
}).catch(error => {
  console.error('下载失败:', error);
});

处理文件名动态获取

如果后端通过响应头返回文件名,可从 response.headers 中解析:

vue axios实现自动下载

const contentDisposition = response.headers['content-disposition'];
let fileName = 'default.pdf'; // 默认文件名

if (contentDisposition) {
  const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/);
  if (fileNameMatch && fileNameMatch[1]) {
    fileName = fileNameMatch[1];
  }
}

封装为可复用方法

src/utils/download.js 中封装通用下载方法:

import axios from 'axios';

export function downloadFile(url, defaultName = 'file') {
  return axios({
    method: 'get',
    url,
    responseType: 'blob'
  }).then(response => {
    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');

    // 尝试从响应头获取文件名
    const disposition = response.headers['content-disposition'];
    let fileName = defaultName;
    if (disposition) {
      const matches = disposition.match(/filename="?(.+)"?/);
      if (matches && matches[1]) fileName = matches[1];
    }

    link.href = downloadUrl;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();

    // 清理资源
    setTimeout(() => {
      window.URL.revokeObjectURL(downloadUrl);
      document.body.removeChild(link);
    }, 100);
  });
}

组件中使用:

import { downloadFile } from '@/utils/download';

// 调用示例
downloadFile('/api/download/file123', 'backup.zip')
  .catch(err => console.error('下载失败', err));

注意事项

  1. 跨域问题:确保后端配置了正确的 CORS 头,特别是 Access-Control-Expose-Headers 需要包含 content-disposition

    vue axios实现自动下载

  2. 大文件处理:对于大文件建议显示下载进度条:

    axios({
    method: 'get',
    url: '大文件地址',
    responseType: 'blob',
    onDownloadProgress: progressEvent => {
     const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
     console.log(`下载进度: ${percent}%`);
    }
    })
  3. POST 请求:如需 POST 方式下载,修改 method 并传递数据:

    axios({
    method: 'post',
    url: '下载接口',
    data: { id: 123 },
    responseType: 'blob'
    })
  4. IE兼容性:IE10 以下需使用 window.navigator.msSaveBlob 替代方案:

    if (window.navigator && window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(blob, fileName);
    } else {
    // 标准实现
    }

以上方法适用于 PDF、Excel、图片等各种文件类型的自动下载场景,通过合理封装可成为项目中的通用下载解决方案。

标签: vueaxios
分享给朋友:

相关文章

vue实现数组

vue实现数组

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

vue diff实现

vue diff实现

Vue Diff 算法实现原理 Vue 的虚拟 DOM Diff 算法(即 patch 过程)是其高效渲染的核心,主要通过对比新旧虚拟节点的差异,最小化 DOM 操作。以下是关键实现要点: 同层级比…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装 scre…

vue实现树

vue实现树

Vue 实现树形结构的方法 使用递归组件实现树形结构 递归组件是Vue中实现树形结构的常见方式。通过组件调用自身,可以轻松构建多层嵌套的树形数据。 <template> <ul…

vue实现拖动

vue实现拖动

Vue实现拖动的常用方法 在Vue中实现拖动功能通常需要结合HTML5的拖放API或第三方库。以下是几种常见实现方式: 使用HTML5原生拖放API HTML5提供了原生拖放API,可以通过drag…

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…