在前端上传多张图片 - OctoberCMS

Uploading multiple images in frontend - OctoberCMS

在前端表单中,我有多个文件上传字段。所以在提交表单时,我在数据库中创建了一条新记录,然后尝试将多个图像附加到它,如下所示:

模型中指定图库的关系 class

public $attachMany = [
    'gallery' => 'System\Models\File',
];

前端表单处理

function onCreate() {
    $data = post();
    
    $newRecord = Record::create($data);
    
    if (Input::hasFile('gallery')) {
        $newRecord->gallery()->create(['data' => Input::file('file_input')]);
    }
}

前端形式HTML

<form method="POST" accept-charset="UTF-8"
      data-request="onCreate" data-request-files data-request-flash>

    <input accept="image/*" name="gallery" type="file" id="gallery" multiple>

</form>

但是,我不断收到以下错误:

SQLSTATE[HY000]: General error: 1364 Field 'disk_name' doesn't have a default value

vendor/october/rain/src/Database/Attach/File.php 中设置 $guarded = [] 没有帮助。

您需要 array file field name gallery[] 来 post 多个文件并在 PHP 端接收它们。

// html changes 
<input accept="image/*" name="gallery[]" type="file" id="gallery" multiple>
//                      HERE       --^ make it array for multiple files 


// PHP side
// $newRecord = ...your code;
if (Input::hasFile('gallery')) {
    foreach(Input::file('gallery') as $file) {

        $fileModel = new System\Models\File;
        $fileModel->data = $file;
        $fileModel->is_public = true;
        // $fileModel->save(); <- save only if you are adding new file to existing record
        // other wise let differ binding handle this 
       
        $newRecord->gallery()->add($fileModel); 
    }     
}
// $newRecord->save();   

它应该可以解决您的问题。

如有任何疑问,请发表评论。