简体   繁体   中英

Yii2 returns error when uploading file to server. Why?

My view:

<?php
    $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>

<?= $form->field($model, 'document_file')->fileInput()->label(Yii::t('app', 'Attachment')) ?>

<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>

My model:

class Documents extends \yii\db\ActiveRecord
{

    public $document_file;

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

}

My controller:

$model = new Documents();
if($model->load(Yii::$app->request->post()) && $model->validate()) {
    $model->document_file = UploadedFile::getInstance($model, 'document_file');
    $model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
} else {
    print_r($model->getErrors());
}
return $this->render('new', compact('model'));

This code is supposed to upload file to server. But I get the error from print_r - it says

Array ( [document_file] => Array ( [0] => Upload a file. ) )

What am I doing wrong and how to upload a file to server???

File attributes ( document_file in your example) could not be assigned via load() , so the value of the following expression is false :

$model->load(Yii::$app->request->post()) && $model->validate()

That is why you got the print error message. You should use UploadedFile::getInstance() to assign the document_file attribute before validate() :

$model = new Documents();
if(Yii::$app->request->isPost) {
    $model->document_file = UploadedFile::getInstance($model, 'document_file');
    if ($model->validate()) {
        $model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
    } else {
        print_r($model->getErrors());
    }
}
return $this->render('new', compact('model'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM