在前端上传多张图片-OctoberCMS

问题描述

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

在模型类中指定的图库的​​关系

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]:常规错误:1364字段“ disk_name”没有 认值

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

解决方法

您需要array file field name gallery[]才能发布多个文件并在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();   

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...