Yii2:提交表单后文件输入引发错误

时间:2018-03-18 14:38:19

标签: php yii2 active-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;
        }
    }

}
?>

错误:

First screenshot

Second screenshot

Third screenshot

2 个答案:

答案 0 :(得分:1)

Instant Solution

更改actionSignup()下方的

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

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

Reason

您上传的文件不是多个文件,因此getInstances()应为getInstance()

About

  

getInstance:返回给定模型的上传文件   属性。该文件应使用上传   [[\ YII \部件\ ActiveField ::的FileInput()]]

     

getInstances:返回给定模型的所有上传文件   属性。

答案 1 :(得分:0)

如果您想上传多个文件 - 在模型的 'maxFiles' > 1 规则中有FileValidator - 将您的属性名称从:

<?= $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