实现文件上传多个yii2不行

Implementation file upload multiple yii2 not work

我正在尝试在 yii2 中实现文件上传多个无效。当我选择2张图片上传时,出现描述"You can upload at most 1 file"。我不知道为什么,以及如何解决?

查看此代码

<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<h1>Gallery</h1>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'] ]) ?>
    <?= $form->field($model, 'image[]')->fileInput(['multiple' => true]) ?>
    <div class="form-group">
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    </div>
<?php
ActiveForm::end();  
?>          

控制器中的代码

public function actionGallery()
        {
            $model = new \app\models\Gallery();
            if (\Yii::$app->request->post()) {
                $model->image = \yii\web\UploadedFile::getInstances($model, 'image');
                    if ($model->validate()) {
                        foreach ($model->image as $file) {
                            $saveTo = 'uploads/' . $file->baseName . '.' . $model->$file->extension;
                                if ($file->saveAs($saveTo)) {
                                    $model2 = new \app\models\Gallery(['image' => $file->baseName . '.' . $file->extension,
                                        ]);
                                    $model2->save(false);
                                }
                            }
                            Yii::$app->session->setFlash('success', 'Success uploaded !');
                        }
                    }
                    return $this->render('gallery', ['model' => $model]);
        }

模型中的代码

<?php

namespace app\models;

use Yii;
use yii\web\UploadedFile;

/**
 * This is the model class for table "gallery".
 *
 * @property integer $id
 * @property string $image
 */
class Gallery extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gallery';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['image'], 'file', 'extensions' => ['png', 'jpg', 'gif'], ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'image' => 'Image',
        ];
    }


}

您应该简单地修复模型的规则,例如:

[['image'], 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxFiles' => 0],

阅读更多关于 FileValidator::$maxFiles 的信息:

$maxFiles : The maximum file count the given attribute can hold. Defaults to 1, meaning single file upload. By defining a higher number, multiple uploads become possible. Setting it to 0 means there is no limit on the number of files that can be uploaded simultaneously.