|
|
OverviewMaking a zip file from multiple source file and make it to be able to download from your browser.
Flow
A sample code
use Archive::Zip;
my @filelist = qw(a.jpg b.txt c.zip d.jpg);
my $zip = Archive::Zip->new();
foreach ($_){
$zip->addFile("$_");
}
my $zipfile = "file.zip";
my $status = $zip->writeToFileNamed("$zipfile");
if ($status != 'AZ_OK') {
unlink("$zipfile") if (-e "$zipfile");
print "Content-Type:text/html\n\n";
print "Cannot make $zipfile";
exit;
}
print "Location: $zipfile\n\n";
Description of the codeuse Archive::Zip; Load Archive::Zip my @filelist = qw(a.jpg b.txt c.zip d.jpg); Make a file list to be zipped. Assuming the files in @filelist are already there. my $zip = Archive::Zip->new(); Make a zip file in the memory. And make an object of the zip file.
foreach ($_){
$zip->addFile("$_");
}
Add each files into the zip file. According to the Archive::Zip document, it takes an array as follows; $zip->addFile(@filelist); it did not work actually. So use addFile one by one.
my $zipfile = "file.zip";
my $status = $zip->writeToFileNamed("$zipfile");
Write out the zip file onto the disk. In this example, the file name is file.zip. If it is succeeded, put the status into $status.
if ($status != 'AZ_OK') {
unlink("$zipfile") if (-e "$zipfile");
print "Content-Type:text/html\n\n";
print "Cannot make $zipfile";
exit;
}
If succeeded, $status contains AZ_OK. Otherwise, it is treated as an error. When failed, the file might be created on the disk. If exist, delete it. The status codes are shown as follows; AZ_OK (0) : All Succeeded AZ_STREAM_END (1) : Stream read succeeded AZ_ERROR (2) : An error AZ_FORMAT_ERROR (3) : Format error while reading a zip file AZ_IO_ERROR (4) : IO error print "Location: $zipfile\n\n"; This allows to download the zip file from the browser. |