【问题标题】:Reading and displaying images from a zip file in react using jszip使用 jszip 从 zip 文件中读取和显示图像
【发布时间】:2020-09-30 17:27:41
【问题描述】:

我有一个 zip 文件,其中包含一些图像、mp4 和一个文本文件。我正在阅读的文本文件是这样的:

      jszip
      .loadAsync(arrayBuffer)
      .then(({ files }) => {
        const txtFiles = Object.entries(files).filter(([fileName]) =>
          fileName.endsWith('.txt'),
        );

        if (!txtFiles.length) {
          throw new Error('No txt files found in archive');
        }

        return txtFiles
          .sort(([a], [b]) => a.length - b.length)[0][1]
          .async('string');
      })

而且效果很好。但我还需要获取文件中的所有图像/mp4,所以我尝试了:

    jszip
      .loadAsync(arrayBuffer)
      .then(({ files }) => {
        const jpgs = [];
        const mediaFiles = Object.entries(files).filter(([fileName]) =>
          fileName.endsWith('.jpg'),
        );

        if (!mediaFiles.length) {
          throw new Error('No media files found in archive');
        }

        mediaFiles.forEach(i => {
          blob = new Blob([i], {
            type: 'image/jpeg',
          });

          img = new Image();
          img.src = URL.createObjectURL(blob);
          jpgs.push(img);
        });

        return jpgs;
      })

现在当我尝试渲染 jpgs 数组时,我得到了一堆像这样的 img 元素:

<img alt="img" src="blob:http://localhost:3000/d64b16c7-aa9c-49a7-96cc-ed4eafc6a054">

但没有图像/损坏的图像图标。我做错了什么?

【问题讨论】:

    标签: reactjs image blob jszip


    【解决方案1】:

    显然我没有正确使用 blob,以下代码为我解决了问题,感谢Loris Bettazza:

    mediaFiles.forEach(([, image]) => {
      image.async('blob').then(blob => {
        const img = new Image();
        img.src = URL.createObjectURL(blob);
        document.body.prepend(img);
      });
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 2018-08-14
      • 1970-01-01
      • 2012-06-12
      • 2016-04-26
      • 2023-03-26
      • 2020-06-22
      • 1970-01-01
      相关资源
      最近更新 更多