js将多个文件打包为压缩包下载

337 阅读1分钟

可以使用 JavaScript 中的 JSZip 库将多个在线附件打包为压缩包,然后使用浏览器的下载功能将其下载到本地。以下是一个示例代码:

首先需安装jszip:

npm install jszip

具体代码:

import JSZip from 'jszip';
import axios from 'axios';

// 假设您有一个名为 attachments 的数组,其中包含多个在线附件的 URL
const attachments = [
  'https://example.com/attachment1.pdf',
  'https://example.com/attachment2.docx',
  'https://example.com/attachment3.jpg',
];

// 创建一个新的 JSZip 实例
const zip = new JSZip();

// 使用 Axios 库下载每个附件,并将其添加到压缩包中
Promise.all(attachments.map((url) => axios.get(url, { responseType: 'blob' })))
  .then((responses) => {
    responses.forEach((response, index) => {
      // 处理每一个文件name
      const filename = `attachment${index + 1}.${response.headers['content-type'].split('/')[1]}`;
      zip.file(filename, response.data);
    });

    // 生成压缩包并将其下载到本地
    zip.generateAsync({ type: 'blob' }).then((content) => {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(content);
      link.download = 'attachments.zip'; // 设置压缩包name
      link.click();
    });
  })
  .catch((error) => {
    console.error(error);
  });

这段代码将创建一个新的 JSZip 实例,并使用 Axios 库下载 attachments 数组中的每个附件。然后,它将将每个附件添加到压缩包中,并使用 generateAsync 方法生成压缩包。最后,它将使用浏览器的下载功能将压缩包下载到本地。请注意,这将创建一个名为 attachments.zip 的文件,并将其保存到浏览器默认的下载目录中。