接口遍历生成md,最终导出zip

126 阅读1分钟

接口请求获取拼接导出的数组markdownFiles

const exportFaq = async () => {
  const markdownFiles = [];
  // 使用 Promise.all 来并行处理所有请求
  await Promise.all(
    tableData.value.map(async item => {
      const { data } = await faq.getDetail({
        faqId: item.id,
        langId: state.langId
      });
      markdownFiles.push({
        name: item.name + '.md',
        content: data.content
      });
    })
  );
  exportZip(markdownFiles);
};

导出的方法,使用第三方库jsZip

import JSZip from "jszip";
import { getNowFormatDate } from "./feedbackExcel";

export const exportZip = (markdownFiles: any[]) => {
  // 2. 创建ZIP文件
  const zip = new JSZip();

  // 3. 向ZIP文件添加Markdown文件
  markdownFiles.forEach((file) => {
    zip.file(file.name, file.content);
  });

  // 4. 生成ZIP文件并下载
  zip.generateAsync({ type: 'blob' }).then((content) => {
    const fileName = 'Faq' + getNowFormatDate() + '.zip'
    const zipFile = new File([content], fileName, { type: 'application/zip' });
    const url = URL.createObjectURL(zipFile);

    // 创建一个a标签用于下载
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.click();

    // 清理临时URL对象
    URL.revokeObjectURL(url);
  });
}