将多个文件下载为 ZIP - Laravel 7

Download multiple files as a ZIP - Laravel 7

如果我dd($files);

我得到了

array:4 [▼
  0 => "/Users/jdoe/Sites/laravel7/public/img/portfolio/58-Admin-Site-Dashboard/126/full.jpg"
  1 => "/Users/jdoe/Sites/laravel7/public/img/portfolio/58-Admin-Site-Dashboard/127/full.jpg"
  2 => "/Users/jdoe/Sites/laravel7/public/img/portfolio/58-Admin-Site-Dashboard/128/full.jpg"
  3 => "/Users/jdoe/Sites/laravel7/public/img/portfolio/58-Admin-Site-Dashboard/130/full.jpg"
]

下载()

public function download($id)
{

    $portfolioImages = PortfolioImage::where('portfolio_id',$id)->get();

    $files = [];
    foreach ($portfolioImages as $i => $portfolioImage) {
        $files[$i] = public_path(). $portfolioImage->image_path;

    }

    // dd($files);

    $zip = new ZipArchive;
    $fileName = $id.'.zip';
    if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
    {

        foreach ($files as $key => $value) {
            $relativeNameInZipFile = basename($value);
            $zip->addFile($value, $relativeNameInZipFile);
        }

        $zip->close();
    }

    return response()->download(public_path($fileName));

}

我一直收到这个错误

ZipArchive::close(): Failure to create temporary file: Permission denied

如何防止此错误?

啊..没关系,发现我自己的问题。

$zipFile = public_path().'/assets/fe/img/portfolio/'.$folderName.'/'.$folderName.'.zip';

工作代码

    public function download($id)
    {

    $portfolioImages = PortfolioImage::where('portfolio_id',$id)->get();

    $files = [];
    foreach ($portfolioImages as $i => $portfolioImage) {
        $files[$portfolioImage->id] = public_path(). $portfolioImage->image_path;

    }

    // dd($files);

    $portfolio  = Portfolio::find($id);
    $folderName = $portfolio->id.'-'.str_replace(' ', '-',$portfolio->name);
    $zip        = new ZipArchive;
    $zipFile    = public_path().'/assets/fe/img/portfolio/'.$folderName.'/'.$folderName.'.zip';

    if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE)
    {

        //add files into a zip
        foreach ($files as $key => $value) {

            //replace word "full" with $portfolioImage->id
            $relativeNameInZipFile = str_replace('full',$key,basename($value));
            $zip->addFile($value, $relativeNameInZipFile);
        }

        $zip->close();
    }

    return response()->download($zipFile);

}

结果✨