UploadedFile::getInstanceByName() doesn't work


(mikex777) #1

In my application i have a code like:
$model->imageFile = UploadedFile::getInstanceByName('imageFile')
I’m 100% sure it worked some time ago but it doesn’t anymore.
$model->imageFile gives always null but it should be an object.
Has something changed in UploadedFile class? Can anyone see what is wrong?

Thank you.

My controller

    public function actionUpload()
    {
        $uploadPath = Yii::getAlias('@frontend') . '/web/uploads/images';
        
        $model = new UploadForm();
        $model->setPath($uploadPath);

        if (Yii::$app->request->isPost) {
            $model->imageFile = UploadedFile::getInstanceByName('imageFile');

            if ($model->upload()) {
                // file is uploaded successfully
                return $this->redirect('/image');
            }
        }
        
        echo json_encode(['error' => $model->errors['imageFile'][0]]);
        exit;
    }

View

     use kartik\file\FileInput;

    <?= Html::label('Dodaj zdjęcia') ?>
    <?= FileInput::widget([
        'name' => 'imageFile',
        'options' => ['multiple' => true],
        'pluginOptions' => [
            'showPreview' => false,
            'uploadUrl' => Url::to(['image/upload']),
            'maxFileCount' => 10
        ]
    ]); ?>

UploadForm.php

    public function upload()
    {
        $filename = $this->imageFile->baseName; // here is the problem: PHP Notice 'yii\base\ErrorException' with message 'Trying to get property 'baseName' of non-object'
        
        if(!file_exists($this->uploadPath)){
            mkdir($this->uploadPath, 0777, true);
        }

        if ($this->validate()) {
            $this->imageFile->saveAs($this->uploadPath . '/' . $filename . '.' . $this->imageFile->extension);
            return true;
        } else {
            return false;
        }
    }

(Alexander Makarov) #2

That depends on what version you was using previously.

Is not uploading allowed? If yes, you should not expect file is always uploaded. Also, you are trying to get file name before validation so there’s no guarantee that file is defined. Solution: move $filename = into if ($this->validate()).


(mikex777) #3

Right, moving $filename = into if ($this->validate()) { is a good point, but i still don’t undestand why UploadedFile::getInstanceByName('imageFile') gives null when $_FILES['imageFile'] is NOT null. What do you mean by Is not uploading allowed? Where should i look into?
My current Yii version is 2.0.20. I don’t know what was the previous version.


(Alexander Makarov) #4

Validation rules.