![](/img/trans.png)
[英]i want to create zip file in cakephp.But my code is not working?
[英]I need to create .Zip file in Laravel and my code does not work
這是我第一次在 StackOverflow 上發帖。 我需要創建一個包含多個圖像的 zip 文件。 我已經嘗試過 Zipper 和 ZipArchive,但我的代碼仍然失敗。
$zip = new \ZipArchive();
foreach ($students as $student) {
$download = 'album' . $student->album_id . '.zip';
if ($zip->open(public_path('albums/' . $student->album_id . '/' . $download), \ZipArchive::CREATE) === TRUE) {
$files = Storage::allFiles('public/albums/' . $student->album_id . '/image_files');
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
}
}
我可以保證所有圖像都存在。 我將圖像放在Storage/app/public/albums/$student->album_id/image_files/
。 請幫我。
首先,您可以添加一個額外的步驟來使用 PHP 內置函數來驗證您的文件是否存在: file_exists()
大多數情況下,如果您的文件不存在,則不會將任何文件添加到zip 中,並且您的代碼將運行而不會引發任何錯誤,但仍然無法運行。
您傳遞給 addFile() 的不是正確的路徑。 addFile() 需要存儲文件的絕對路徑。 您需要添加這一行$file_path = storage_path("app/{$file}");
見下面的代碼:
$zip = new \ZipArchive();
foreach ($students as $student) {
$download = 'album' . $student->album_id . '.zip';
if ($zip->open(public_path('albums/' . $student->album_id . '/' . $download), \ZipArchive::CREATE) === TRUE) {
$files = Storage::allFiles('public/albums/' . $student->album_id . '/image_files');
foreach ($files as $file) {
$file_path = storage_path("app/{$file}");
if (file_exists($file_path)) {
$zip->addFile($filepath);
}
}
$zip->close();
}
}
或者,如果您希望下載任何壓縮文件,您可以在代碼末尾返回下載響應以進行下載:
return response()->download(public_path('albums/' . $student->album_id . '/' . $download));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.