繁体   English   中英

我正在尝试将多个图像下载为 zip 文件,但使用 laravel 7 时出错

[英]I am trying to download multiple image as a zip file but getting error using laravel 7

我正在尝试将多个图像下载为 zip 文件,但出现错误foreach() 提供的参数无效,请帮助我如何解决该问题,谢谢。 在此处输入图片说明

检查错误: https : //flareapp.io/share/47qG2A3m

控制器

public function dowloads($id)
{
    $url = config('yourstitchart.file_url');
    
    $zip = new ZipArchive;
    $inboxFiles = Inbox::where('id', $id)->first()->file;

    // $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"

    foreach ($inboxFiles as $file) {
        $zip->add($url . $file); // update it by your path
    }
    $zip->close();
    
    return response()
        ->download(
            public_path('/temporary_files/' . "deals.zip"),
            "deals.zip",
            ["Content-Type" => "application/zip"]
        );
}

你正在返回一个字符串,你不能像数组一样处理它。

它是 JSON,你可以使用:

$inboxFiles = json_decode(Inbox::where('id', $id)->first()->file);

(上面的代码不是很健壮,但你有办法)

我知道这已经回答了,但不要使用json_decode在Laravel更多...

铸造领域的file作为JSON / array ,所以它会自动将一个数组,当你将它保存在数据库中,它会转化为JSON,当你想读回,它会自动转换为数组。 ..

为此,您必须编辑Inbox模型并添加此属性:

protected $casts = ['file' => 'array'];

就是这样,然后您必须像使用该字段一样使用该字段,就好像它已经是一个数组一样,因此将您的代码保留在您的问题中,无需任何编辑,它将立即起作用:

public function dowloads($id)
{
    $url = config('yourstitchart.file_url');
    
    $zip = new ZipArchive;
    $inboxFiles = Inbox::where('id', $id)->first()->file;

    // $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"

    foreach ($inboxFiles as $file) {
        $zip->add($url . $file); // update it by your path
    }
    $zip->close();
    
    return response()
        ->download(
            public_path('/temporary_files/' . "deals.zip"),
            "deals.zip",
            ["Content-Type" => "application/zip"]
        );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM