vue 后端返回文件流,前端导出下载

vue 后端返回文件流,前端导出下载

  1. 配置axios响应拦截器
js 复制代码
request.interceptors.response.use(
  (response) => {
    const res = response.data
    // 关键代码: 返回的是文件流
    if (res instanceof Blob) {
      return response
    }

    if (res.code == 200 || res == true) {
      return res
    } else {
      Message.error("连接超时")
      return Promise.reject(res)
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)
  1. 配置api响应类型
js 复制代码
export async function fileExport(params) {
  return request({
    url: "/api/file/export",
    method: "post",
    data: params,
    responseType: 'blob', // 配置响应类型
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}
  1. 封装解码下载的方法
js 复制代码
downloadFile(res) {
  const fileNames = res.headers["content-disposition"];
  if (fileNames) {
    //解码
    const fileName = decodeURIComponent(fileNames.match(/=(.*)$/)[1]);
    // 处理返回的文件流
    const content = res.data;
    const blob = new Blob([content], {
      type: "application/octet-stream; charset=utf-8",
    });
    if ("download" in document.createElement("a")) {
      //非IE下载
      const a = document.createElement("a"); //创建一个a标签
      a.download = fileName; //指定文件名称
      a.style.display = "none"; //页面隐藏
      a.href = URL.createObjectURL(blob); // href用于下载地址
      document.body.appendChild(a); //插到页面上
      a.click(); //通过点击触发
      URL.revokeObjectURL(a.href); //释放URL 对象
      document.body.removeChild(a); //删掉a标签
      this.$message.success("下载成功");
    } else {
      //IE10 + 下载
      navigator.msSaveBlob(blob, fileName);
      this.$message.success("下载成功");
    }
  }
},
  1. 发起下载请求
js 复制代码
fileExport({}).then((res) => {
  // 下载文件
  this.downloadFile(res);
}).catch((err) => {});
  1. 后端返回的内容示例
js 复制代码
PK-q�cfgfW�d�q�ZCB|��|�*�*h㻆},^�{Va�^K<4�6�N�XQ�dž�9�!P��$��҆�d�c�D�j);��ѝP�g��E�M'O�ʕ����H7L�h���R���G��^�'�{��zސʮB��3�˙��h.�h�W�жF�j娄CQՠ똈���}ιL�U:D�����%އ����,�B���[�	�� ;˱�	�{N��~��X�p�ykOL��kN�V��ܿBZ~����q�� �ar��{O�PKz��q;�S��M�~s+q�~�>�y�ƹXp`=G��C�q-rh?�ڏ�v��=��_M���5o]���2�`g�	��bb48G_��PKMMr�
相关推荐
excel1 分钟前
Vue 模板编译中的 srcset 机制详解:从 HTML 语义到编译器实现
前端
excel1 分钟前
🌐 从 Map 到 LRUCache:构建智能缓存工厂函数
前端
excel2 分钟前
Vue 模板编译中的资源路径转换:transformSrcset 深度解析
前端
excel10 分钟前
Vue 工具函数源码解析:URL 解析与分类逻辑详解
前端
excel13 分钟前
Vue SFC 样式预处理器(Style Preprocessor)源码解析
前端
excel14 分钟前
深度解析:Vue Scoped 样式编译原理 —— vue-sfc-scoped 插件源码详解
前端
excel16 分钟前
Vue SFC Trim 插件源码解析:自动清理多余空白的 PostCSS 实现
前端
excel20 分钟前
Vue SFC 样式变量机制源码深度解析:cssVarsPlugin 与编译流程
前端
excel22 分钟前
🧩 Vue 编译工具中的实用函数模块解析
前端
excel26 分钟前
🧩 深入剖析 Vue 编译器中的 TypeScript 类型系统(第五篇)
前端