我需要在 Laravel 中创建 .Zip 文件,但我的代码不起作用

问题描述 投票:0回答:1

这是我第一次在 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 laravel zip php-ziparchive
1个回答
1
投票

首先,您可以添加一个额外的步骤来使用 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));
© www.soinside.com 2019 - 2024. All rights reserved.