Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip files / folders / zips from Remote URLs with JSZip

Tags:

reactjs

zip

jszip

Was stuck on this for a little bit and managed to overcome the problem and wanted to share incase anyone else encounters this in the future.

The function is used as an onClick for a button on the site, when the button is clicked, it needs to grab all the corresponding .zip files from individual remote urls (a CMS) and bundle into a singular .zip to then be downloaded to the user.

See answer below for the code.

like image 513
Oliver Heward Avatar asked Sep 13 '25 19:09

Oliver Heward


1 Answers

import JSZip from 'jszip';
import { saveAs } from 'file-saver';

//.... some react component

  const handleZipDownload = async () => {
    var zip = new JSZip();
    
    // block.packages is an array of items from the CMS
    const remoteZips = block.packages.map(async (pack) => {

      // pack.file.url is the URL for the .zip hosted on the CMS
      const response = await fetch(pack.file.url);
      const data = await response.blob();

      // pack.kitName is from a loop, replace with your file name.
      zip.file(`${pack.kitName}.zip`, data);

      return data;
    })

    Promise.all(remoteZips).then(() => {
      zip.generateAsync({ type: "blob" }).then((content) => {
        saveAs(content, `your-pack-name.zip`);
      })
    })
  }

//... rest of component + JSX

like image 93
Oliver Heward Avatar answered Sep 17 '25 19:09

Oliver Heward