Yii2:文件输入在提交表单后抛出错误

Yii2 : File Input throws error after submitting form

当我点击“注册”按钮时,我收到以下错误:数组到字符串的转换。 我认为错误发生在我调用 fileInput() 方法时,但我不知道如何解决它。
这是视图的部分代码

<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>

<?= $form->field($model, 'password')->passwordInput() ?>

<?= $form->field($model, 'email') ?>


<?= $form->field($modelUpload, 'imageFile')->fileInput() ?>

<div class="form-group">
    <?= Html::submitButton('Signup', ['class' => 'btn', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>

虽然这是控制器的代码:

    <?php

class SiteController extends Controller {

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup() {
        $model = new SignupForm();
        $modelUpload = new UploadForm();
        if ($model->load(Yii::$app->request->post()) && $modelUpload->load(Yii::$app->request->post())) {
            $modelUpload->imageFile = UploadedFile::getInstances($modelUpload, 'imageFile');

            if ($user = $model->signup()) {

                if (Yii::$app->getUser()->login($user) && $modelUpload->upload()) {

                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
                    'model' => $model,
                    'modelUpload' => $modelUpload,
        ]);
    }

}

这是模型的代码。和官方文档一样。

<?php

class UploadForm extends Model {

    /**
     * @var UploadedFile
     */
    public $imageFile;

    public function rules() {
        return [
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    public function upload() {
        if ($this->validate()) {
            $this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
            return true;
        } else {
            return false;
        }
    }

}
?>

错误:

Instant Solution

从下方

更改 actionSignup() 内的行
UploadedFile::getInstances($modelUpload, 'imageFile');

UploadedFile::getInstance($modelUpload, 'imageFile');

Reason

您上传的只是一个文件,而不是多个文件,因此 getInstances() 应该是 getInstance()

About

getInstance : Returns an uploaded file for the given model attribute. The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]]

getInstances: Returns all uploaded files for the given model attribute.

如果您想上传 多个 文件 - 在模型的 FileValidator 规则中包含 'maxFiles' > 1 - 更改您的 属性名称 来自:

<?= $form->field($modelUpload, 'imageFile')->fileInput() ?>

<?= $form->field($modelUpload, 'imageFile[]')->fileInput() ?>

读这个: https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload#uploading-multiple-files