后端返回Blob文件流,前端实现导出

  1. 拦截器修改

    // 检查响应是否为blob类型
    if (response.data instanceof Blob) {
    return response;
    } else {
    // 正常对象
    if (res.returnCode == 200) {
    return res;
    } else {
    // 错处理
    }
    }

  2. 接口处理,返回数据类型设置为 responseType: "blob"

3.导出函数

复制代码
// 导出
    output() {
      let data = {};
      if (this.status) {
        data.status = this.status * 1;
      }
      downExcel(data).then((response) => {
        const disposition = response.headers["content-disposition"];
        let filename = this.parseFilenameFromDisposition(disposition);
        this.$message({
          message: "导出成功!",
          type: "success",
        });
        // 创建 Blob 对象
        const blob = new Blob([response.data]);
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", filename); // 设置下载文件名
        document.body.appendChild(link);
        link.click();
        // 清理DOM和对象URL
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      });
    },
  1. 解析后端在content-disposition中返回的文件名称

    parseFilenameFromDisposition(contentDisposition) {
    if (!contentDisposition) {
    return "download";
    }
    const filenameRegex =
    /(?:filename|fileName)[;=\n]*=((['"]).*?\2|[;\n]*)/;
    const matches = filenameRegex.exec(contentDisposition);
    if (matches && matches[1]) {
    // 提取文件名并去除引号
    let filename = matches[1].replace(/['"]/g, "");
    // 尝试解码URL编码的文件名
    try {
    filename = decodeURIComponent(filename);
    } catch (e) {
    console.warn("文件名解码失败:", e);
    }
    return filename;
    }
    return "download";
    },

相关推荐
FreeTinker4 小时前
HTML本地存储技术解析:localStorage与sessionStorage的原理、差异与应用场景
前端·html
qq_452396234 小时前
第十二篇:《全链路监控与可观测性:前端错误追踪与性能分析》
前端
wangruofeng5 小时前
Phosphor Icons 官网源码拆解:URL 即存储、水波动画与 7362 Star 图标库的架构实践
前端·架构·github
BigTopOne6 小时前
WebRTC Native / Android 开发学习资源整理
前端
excel7 小时前
nuxt 3 升级 nuxt 4 报错之 hasInjectionContext
前端
何以解忧,唯有..7 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
软件聚导航8 小时前
「聚小软 AI 助手」技术升级:从数据库检索到 RAG 知识库问答
前端·数据库·mysql·微信小程序·小程序·ai编程·rag
恋猫de小郭8 小时前
看懂大模型架构术语,帮助你理解目前常见的大模型开源架构
前端·人工智能·ai编程
yma168 小时前
通过提示词实现GitHub Pages 和 Nginx 双部署竟然这么简单?
前端
前端 贾公子9 小时前
第09章:上下文与记忆 (2)
java·服务器·前端