Upload image to Yii

I implemented uploading image files in the Yii framework. It uploads the image and saves to the database successfully, but the images are not stored in my directory. In my controller, I added the following code:

public function actionCreate()
{
    $model=new Friends;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Friends']))
    {
        $model->attributes=$_POST['Friends'];

                 $image=CUploadedFile::getInstance($model,'profile_image');
             if (is_object($image) && get_class($image)==='CUploadedFile') 
                {
                  $model->profile_image=$image->name;    
                }
                if($model->save())
            if(is_object($image))
            $image->saveAs(dirname(__FILE__).'/../../friends_picture/'.$model->profile_image);   

        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}


Where is the mistake? Is the name of the specified directory true or not?

+3
source share
2 answers

Try this code.

public function actionCreate()
{
    $model=new Friends;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Friends']))
    {
        $model->attributes=$_POST['Friends'];

        $model->profile_image = CUploadedFile::getInstance($model,'profile_image');

        if($model->save())

            $fullImgSource = Yii::getPathOfAlias('webroot').'/friends_picture/'.$model->profile_image;
            $model->profile_image->saveAs($fullImgSource);


        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

May this help you.

thank

+3
source

just try this

$ model-> profile_image = CUploadedFile :: getInstance ($ model, 'profile_image');

    if($model->save())

        $fullImgSource = Yii::getPathOfAlias('webroot').'/friends_picture/'.$model->profile_image;
        $model->profile_image->saveAs($fullImgSource);
0
source

All Articles