Reputation: 21
I have a issue with Yii2 and multiple download. I'm using Fpdf to generate PDF and save them on a folder. This is ok, but when I try to download all of them from that folder, he just return me one file, the first one:
for($x = 1; $x <= $vlt; $x++){
if (file_exists($tempPath.'Client'.$x.'.pdf')) {
Yii::$app->response->sendFile($tempPath.'Client'.$x.'.pdf');
}
}
I don´t understand why this happen.
Thank you.
Upvotes: 1
Views: 1439
Reputation: 23748
This aint happening friend, You should zip all files and then download them rather than trying to download them like this SEE WHY
.
You should instead zip and download all the files, you can use ZipArchive
class to achieve this, change your above code so that all your zip files are added into a single ZIP and then download that zip file.
Just remember that
1) The below script uses a temp folder inside your project root with the name tmp
to create the zip file and download, adjust your path accordingly for $zipname
if you want to use some other directory.
2) You should provide the complete path in the $tempPath
so that the files are added successfully to the zip file.
//set zip file name for download
$zipFilename = md5('file-' . time()) . '.zip';
//zip file name with path
$zipPath = Yii::$app->basePath . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $zipFilename;
//start adding the files into the zip archive
$zip = new \ZipArchive();
//open zip archive
$zip->open($zipPath, \ZipArchive::CREATE | ZipArchive::OVERWRITE);
for ($x = 1; $x <= $vlt; $x++) {
if (file_exists($tempPath . 'Client' . $x . '.pdf')) {
$zip->addFile(realpath($tempPath . DIRECTORY_SEPARATOR . 'Client' . $x . '.pdf'), 'Client' . $x . '.pdf');
}
}
//close the zip file
$zip->close();
//return zip archive name without path
Yii::$app->response->sendFile($zipPath);
Upvotes: 2