Create and download zip file with AJAX

Zip file creation is a better way to enable the user to download multiple files in one package. This may affect the page load time according to the number of files and their size.

Arises more problem when need to create multiple zip files on page load for download.

To avoid this type of problem you can either use only PHP or jQuery AJAX to create and download the zip file when it’s required.

In this tutorial, I am using jQuery AJAX.

Create and download zip file with AJAX


Contents

  1. HTML
  2. PHP
  3. jQuery
  4. Demo
  5. Conclusion

 


 

1. HTML

Creating a single button for download.

Completed Code

<body>
 <input type='button' id='download' value='Download'>
</body>

 

2. PHP

Create a new ajaxfile.php and an archive and includes directory. The archive is for storing the created zip files and in the includes directory stored some files.

Read files of includes directory and add in $zip object. After adding files to the $zip object return the path of the created zip file.

Completed Code

<?php
$zip = new ZipArchive();
$filename = "archive/myzipfile.zip";

if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
  exit("cannot open <$filename>\n");
}

$dir = 'includes/';

// Create zip
if (is_dir($dir)){

 if ($dh = opendir($dir)){
   while (($file = readdir($dh)) !== false){
 
     // If file
     if (is_file($dir.$file)) {
       if($file != '' && $file != '.' && $file != '..'){
         $zip->addFile($dir.$file);
       }
     }
 
   }
   closedir($dh);
  }
}

$zip->close();

echo $filename;

 

3. jQuery

On the download button click send an AJAX request to create the zip file and get the file path.

Open the path in a new tab using window.location which gets from AJAX successfully callback for download.

Completed Code

$(document).ready(function(){
 $('#download').click(function(){
   $.ajax({
     url: 'ajaxfile.php',
     type: 'post',
     success: function(response){
       window.location = response;
     }
   });
 });
});

 

4. Demo

Click on the download button.


 

5. Conclusion

Prefer this type of file creation and download when there is a long list of records with download option.

Otherwise, simply use PHP to create file while data loading on the page.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *