导出/下载 get post

76 阅读1分钟

导出/下载----->get/post请求

  • get
utils

export const appendObjectToUrl = (url, obj) => {
  const query = Object.keys(obj)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
    .join("&");
  const separator = url.includes("?") ? "&" : "?";
  const modifiedUrl = `${url}${separator}${query}`;
  return modifiedUrl;
};

调用

const downloadUrl = `路径`;
const query = {
    参数
};
const url = appendObjectToUrl(downloadUrl, query);
window.open(url);

  • post
api封装

export const exportNoteList = (data) =>
  http({
    url: 请求路径,
    headers: {
      httpWhite: true,
    },
    responseType: "blob", // 文件流
    rawresp: true,//用户获取到原始数据
    method: "post",
    data,
  });


调用

// 导出
    handleExport() {
this.$message.error("条件不能为空");
      const query = {
      参数
      };
      exportNoteList(query)
        .then((res) => {
          if (res.status == 200) {
            downloadDataTemplate(res);
          }
        })
        .catch((error) => {
          console.error("导出失败:", error);
        });
    },
    
    

   utils
   
   
    downloadDataTemplate(res) {
      let fileName = "导出数据.xlsx";
      const contentDisposition = res.headers["content-disposition"];
      if (contentDisposition && contentDisposition.includes("filename=")) {
        // fileName = decodeURIComponent(contentDisposition.split('filename=')[1]);
          
        //  正常处理filename只需要上面
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(contentDisposition);
        if (matches != null && matches[1]) {
          fileName = decodeURIComponent(matches[1].replace(/['"]/g, ""));
        }
      }

      const blob = new Blob([res.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
      });
      const downloadElement = document.createElement("a");
      const href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = fileName; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放blob对象
    },