jsZip – Création d’un ZIP depuis le navigateur

Aucun code n’est requis côté serveur pour générer le zip !

Télécharger l’exemple

Exemple de code source :

<html>
   <head>    
      <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
      <script type="text/javascript" src="jszip.js"></script>
      <script type="text/javascript" src="jszip-utils.js"></script>
      <script type="text/javascript" src="FileSaver.js"></script>
   </head>  
   <body>
      <p>Create and download a zip file</p>
      <button id="blob" class="btn btn-primary">click to download</button>

      <script>

         /**
          * Fetch the content and return the associated promise.
          * @param {String} url the url of the content to fetch.
          * @return {Promise} the promise containing the data.
          */
         function urlToPromise(url) {
             return new Promise(function(resolve, reject) {
                 JSZipUtils.getBinaryContent(url, function (err, data) {
                     if(err) {
                         reject(err);
                     } else {
                         resolve(data);
                     }
                 });
             });
         }

         var zip = new JSZip();
         zip.file("Hello.txt", "Bonjour le monde\n");

         // Generate a directory within the Zip file structure
         var img = zip.folder("images");

         // Add a file to the directory, in this case an image with data URI as contents
         img.file("1.png", urlToPromise('http://localhost:8080/test/images/1.png'), {base64: true});
         img.file("2.png", urlToPromise('http://localhost:8080/test/images/2.png'), {base64: true});
         img.file("3.png", urlToPromise('http://localhost:8080/test/images/3.png'), {base64: true});
         img.file("4.png", urlToPromise('http://localhost:8080/test/images/4.png'), {base64: true});
         img.file("5.png", urlToPromise('http://localhost:8080/test/images/5.png'), {base64: true});

         jQuery("#blob").on("click", function () {
             zip.generateAsync({type:"blob"}).then(function (blob) { // 1) generate the zip file
                 saveAs(blob, "hello.zip");                          // 2) trigger the download
             }, function (err) {
                 jQuery("#blob").text(err);
             });
         });
      </script>

   </body>   
</html>