后端返回文件流,前端实现下载功能

时间:2025-03-28 10:10:57

1,接口设置 responseType: "blob"

export function sopExportPDF(id) {
  return request({
    url: "/tb/procedure/export/pdf/" + id,
    responseType: "blob",
    method: "get",
  });
}

2. 项目安装downloadjs

npm install downloadjs

3.需要的页面引入模块

import download from "downloadjs";

4.在接口函数中创建blob对象,并调用download方法

    // 导出单个sop
    async ExportPDF(id, name) {
      let res = await sopExportPDF(id);
      let blob = new Blob([res], { type: "applictation/pdf" });
      download(blob, name + ".pdf", "application/pdf");
      // let href = (blob);
      // let a = ("a");
      //  = "none";
      //  = href; // 指定下载链接
      //  = name + ".pdf"; //指定下载文件名
      // (); //触发下载
      // (); //释放URL对象
    },

注意:文件下载后无法打开或者损坏请检查接口api是否添加:responseType: "blob"

后端返回文件流获取文件名称

1.在使用的文件中引入axios并配置

import axios from "axios";
["Authorization"] = "Bearer " + getToken();
["Content-Type"] = "application/json;charset=utf-8";

2.在函数中使用axios发送接口

 // 导出单个sop
    ExportPDF(id, name) {
      axios({
        url: .VUE_APP_BASE_API + "/tb/procedure/export/pdf/" + id,
        responseType: "blob",
        method: "get",
      }).then((response) => {
        (response);
        let dispositionStr = ["content-disposition"];

        // 获取文件名
        let dispositionArr = (";");
        // 获取文件名

        let fileName = decodeURIComponent(dispositionArr[1]);
        fileName = ("=")[1];
        let blob = new Blob([], { type: "applictation/pdf" });
        download(blob, fileName, "application/pdf");
      });

注意:后端一定要配置content-disposition响应头!!!