Laravel:上传多个图像到现有

问题描述 投票:0回答:1
$pricelists = [];
        $pricelistcount = 1;
        if ($request->hasFile('project_pricelist_url')) {

            $existingPricelists = $project->project_pricelist_url ?: [];
             foreach ($existingPricelists as $existingPricelist) {
                 Storage::delete('public/project/pricelists/' . $existingPricelist);
             }

             foreach ($existingPricelists as $existingFilename) {
                 $pricelists[] = $existingFilename; // Add existing filenames to the new array
             }





            foreach ($request->file('project_pricelist_url') as $file) {
                $currentDateTime = now()->format('YmdHis');
                $filename = $initials . "_" . $pricelistcount . '_' . $currentDateTime . '.' . $file->getClientOriginalExtension(); // Buat nama unik untuk setiap file
                $file->storeAs('public/project/pricelists', $filename); // Simpan file ke direktori yang diinginkan
                $pricelistcount++;
                $pricelists[] = $filename; // Simpan nama file dalam array
            }
            $project->project_pricelist_url =  json_encode($pricelists);

        }

有什么帮助吗?

在上传新图像时尝试这种方式,它从现有文件中返回空字符串

[{},"new_image_path"]

也尝试过 json_decode ,但是返回

json_decode(): Argument #1 ($json) must be of type string, array given

laravel laravel-storage
1个回答
0
投票

第一个错误,三元运算符只有 else 部分

第二个错误,使用publi_path代替save

尝试下面的代码,希望这有帮助

if ($request->hasFile('project_pricelist_url')) {

    $existingPricelists = $project->project_pricelist_url ? $project->project_pricelist_url : [];
    
    foreach ($existingPricelists as $existingPricelist) {
        Storage::delete('public/project/pricelists/' . $existingPricelist);
    }

    foreach ($existingPricelists as $existingFilename) {
        $pricelists[] = $existingFilename; // Add existing filenames to the new array
    }

    foreach ($request->file('project_pricelist_url') as $file) {
        $currentDateTime = now()->format('YmdHis');
        $filename = $initials . "_" . $pricelistcount . '_' . $currentDateTime . '.' . $file->getClientOriginalExtension(); // Buat nama unik untuk setiap file
        $file->move(public_path('project/pricelists'), $filename); // Simpan file ke direktori yang diinginkan
        $pricelistcount++;

        $pricelists[] = $filename; // Simpan nama file dalam array
    }
    
    $project->project_pricelist_url = json_encode($pricelists);
}
© www.soinside.com 2019 - 2024. All rights reserved.