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 problems 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 file.

Also, create 2 directories –

  • includes – In this directory store some files that need to be compressed.
  • archive – This directory is used to store the created zip files.

Create a ZipArchive class object.

Specify zip file location in $filename variable.

Read files of includes directory and add in $zip object using addFile().

Return the path of zip file – $filename.

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

Send an AJAX request on download button click to create the zip file and get the file path.

On successful callback pass response in window.location to open link in new tab 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 zip file while data loading on the page.

If you found this tutorial helpful then don't forget to share.