Can't upload files reliably?

I got this method that’s intended to upload a file, but sometimes it does so when $this->imageFile is not instantiated. I have no idea why.


public function upload()

{


    $path = Url::to('@webroot/images/photos/');

    $filename = strtolower($this->username) . '.jpg';

    $this->imageFile->saveAs($path . $filename);




    return true;


}

I call the method upload() in beforeSave() like this:




public function beforeSave($insert)

{


    if(parent::beforeSave($insert)){


        if($this->isNewRecord)

        {

            $this->password = Yii::$app->security->generatePasswordHash($this->password);

        }


        $this->upload();

        return true;

    }

    else

    {

        return false;

    }

}

I called this method like 100 times with mixed results. I have no idea why this method call doesn’t give the same result. It should either never work or always work, but for some reason the code is not deterministic at all.


public function actionCreate()

{

    $model = new Member();

    $model->imageFile = UploadedFile::getInstance($model, 'imageFile');




    if ($model->load(Yii::$app->request->post()) && $model->save()) {




        return $this->redirect(['view', 'id' => $model->id]);

    } else {

        return $this->render('create', [

            'model' => $model,

        ]);

    }

}



Another thing, when I use this code, I get a file, but the username is blank so I get a .jpeg file without a name.


    public function actionCreate()

    {

        $model = new Member();

		$model->imageFile = UploadedFile::getInstance($model, 'imageFile');

		$model->upload(); 

		


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

			

			

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }

Try this and this links, may be helpful…

In the above, model is a new model so $model->username is blank. Try upload() after $model->load