Zip and download selected files

ASP.NET, PHP, Tutorials

This tutorial covers a simple but common need. You have a page with a list of files and want your users to select and download multiple files at once. In this example, we will use the upload field that can store multiple files at once.


In Page Designer proceed to the List page and add a Custom button.

ClientBefore event

In this event, we simply check if any records were actually selected and display a message if there is nothing to process.

if ($("[name^=selection]:checked").length<1) {
  swal("Select at least one record");
  return false;
}

Server event

In this event, we build the list of files and zip them up. We save the zip file in the temporary folder (templates_c) and pass the name of the file to Client After event. If something didn't work we just pass the error message to the same event.

PHP code

$filesArray = array();
while($record = $button->getNextSelectedRecord()){
	$files = my_json_decode($record["files"]);
	foreach($files as $f){
		$filesArray[] = $f;
	}
}
$zip = new ZipArchive();
$filename = "templates_c\\DownloadSelected".date("YmsHis").".zip";
$result["error"] = "";
$result["name"] = $filename;
if($zip->open(getabspath($filename), ZipArchive::CREATE)!==TRUE) {
    $result["error"] = "Cannot create zip file";
}

foreach($filesArray as $v)
	$zip->addFile(getabspath($v["name"]),$v["usrName"]);

Client After event

Here we display the error message if any. If there is no error message we simply redirect the user to the zip file and it will be downloaded automatically. Then we clear all the checkboxes so the page is ready for the next step.

if(result["error"]!="")
	ajax.setMessage(result["error"]);
else{
	location.href=result["name"];
	$("[name^=selection]").each(function(){
		$(this).prop("checked","");
	});
}

1 thought on “Zip and download selected files

  1. Perfect timing again… Was considering how to do this. You must be a mind reader..

    Thanks again…

Leave a Reply

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