首页 > 解决方案 > Angular 4将base64图像数组下载为ZIP文件

问题描述

我正在使用 Typescript 使用 Angular2 v4 应用程序,我需要一种将许多图像(base64 格式)下载到 Zip 文件中的方法。

例如:我有一个这样的数组(例如假 base64 图像)

data = [
  'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA ...',
  'data:image/png;base64, iVBTYu0KGgoBBBBNSUhYUgJJJJUA ...',
  'data:image/png;base64, CGBHHFGY0goAAAANSUhEUgAAAAUA ...',
  ...
]

我需要一种方法来下载它,首先将每个图像转换为 .jpg 或 .png 图像,然后编译所有图像并下载为 zip 文件。像这样的东西(我不知道代码,我只需要这样的东西)

downloadZip() {
  const arrayAsJPG = [];
  this.data.forEach(i => {
    const imageInJpg = i.convertToJPGfile(); // this is not code, this is a function that converts the base64 to a jpg file
    arrayAsJPG.push(imageInJpg);
  });
  ZipFileSaver.save(arrayAsJPG, 'myImageReport.zip'); // this isn't code neither, just and interpretation of what I need

}

有什么办法可以做到吗?

标签: angularimagetypescriptdownloadzip

解决方案


@gary 给出了很好的解释。我在stackoverflow上找到了一些例子:

是否可以在 Angular 4 中生成 zip 文件并下载?

在 javascript 中将 base64 转换为 blob 也可以使用@types/jszip.

我构建了一个执行以下操作的示例:

  • 它从 API(模拟)中获取您描述的数组;
  • 它将该数组的每个项目转换为一个 blob;
  • 它将 blob 作为文件添加到 zip 文件中;
  • 最后创建zip文件;
  • 我只有 png base64,所以将其更改为 jpg。

https://stackblitz.com/edit/angular-jzqtr​​k?file=src%2Fapp%2Fapp.component.ts


推荐阅读