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�
相关推荐
GISer_Jing10 分钟前
Nano Banana:AI图像生成与编辑新标杆
前端·javascript·人工智能
csdn_aspnet17 分钟前
用100行實現HTML5可存檔塗鴉版
javascript
布茹 ei ai22 分钟前
城市天气查询系统 (City Weather Dashboard)
javascript·vue.js·html·css3·开源软件·天气预报
gyx_这个杀手不太冷静24 分钟前
上线前不做 Code Review?你可能正在给团队埋雷!
前端·代码规范·团队管理
全栈老石43 分钟前
从硬编码到 Schema 推断:前端表单开发的工程化转型
前端·vue.js·架构
weixin_462446231 小时前
【原创实践】使用 shell 脚本批量创建 Linux 用户并生成随机密码
linux·服务器·前端
软件技术NINI1 小时前
娃娃店html+css 4页
前端·css·html
VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue乡村振兴服务系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
wordbaby1 小时前
TanStack Router 路径参数(Path Params)速查表
前端
梵尔纳多1 小时前
Electron 主进程和渲染进程通信
javascript·arcgis·electron