-1

When i am trying to upload imgage file to projectfolder\uploaded directory i got error

Fatal error: Call to a member function saveAs() on string

My controller code is as below

public function actionStore()
{       
    $model = new Article;

    $this->performArticleValidation($model);

    $userId = Yii::app()->user->getId();                

    if(isset($_POST['Article'])) {          
        $model->attributes = $_POST['Article'];
        $model->avatar = CUploadedFile::getInstance($model,'avatar');
        //var_dump($model->avatar); // Outside if
        if($model->save()) {
            //var_dump($model->avatar); // Inside if
            $path = Yii::app()->basePath . '/../uploaded';      
            $model->avatar->saveAs($path);
            EUserFlash::setSuccessMessage('Thank you.');
            $this->redirect(array('index'));
        }
    }
}

Model is as below

public function rules() {        
    return array(
        array(['avatar'], 'file', 'skipOnEmpty' => false, 'types' => 'jpg, jpeg, gif, png'),
    );

}

When I tried to debug $model->avatar outside if condition it gives me an array of an object as shown in below image and inside if it gives me the string.

form attribute for image upload is avatar enter image description here

benomatis
  • 5,536
  • 7
  • 36
  • 59
Nileshsinh Rathod
  • 948
  • 1
  • 17
  • 37

2 Answers2

-1

$model->avatar->saveAs($path);

here you are trying to call saveAs() on avatar

but somehow instead of an object avatar is a string. maybe avatar was always a string.

var_dump($model->avatar)

would produce a string.

that is what the error message shows

Shobi
  • 10,374
  • 6
  • 46
  • 82
-1

I forgot to pass file name in saveAs() i am just passing directory path only so image not uploaded.

public function actionStore()
{
    $model = new Article;

    $this->performArticleValidation($model);

    $userId = Yii::app()->user->getId();                

    if(isset($_POST['Article'])) {

        $model->attributes = $_POST['Article'];
        $model->created_at = date('Y-m-d H:i:s',time());

        $uploadedFile = CUploadedFile::getInstance($model, 'avatar');
        $model->avatar = strtotime("now").'.'.$uploadedFile->getExtensionName();
        $model->created_by = $userId;

        if($model->save()) {    

            $path = Yii::app()->basePath.'\..\uploaded\articles';
            $uploadedFile->saveAs($path.'/'.$model->avatar);

            EUserFlash::setSuccessMessage('Thank you.');
            $this->redirect(array('index'));
        }
    }
}
Nileshsinh Rathod
  • 948
  • 1
  • 17
  • 37