FSShaikh
FSShaikh

Reputation: 125

yii framework: how to save image with unique id in the /image folder?

I am saving image into the /image folder and image of image in the database.

but problem is i am creating unique id name for the image by which in the database it saves image name as new generated name by uniqueid function but in /image folder it saves image with the original name.

controller code is--

public function actionCreate()
{
    $model=new Add;
    //$model->createtime = strtotime('Now');
    //$model->createtime=time();

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

    if(isset($_POST['Add']))
    {
        $model->attributes=$_POST['Add'];
        $model->createtime=date("d m y G:i:s ");
        $model->username=Yii::app()->user->name;
        $model->image=CUploadedFile::getInstance($model,'image');
        if($model->save())
        {
            if($model->image !== null)
                    {
                        $image=CUploadedFile::getInstance($model,'image');
                        $model->image = uniqid() . '.jpg';
                        $image->saveAs( Yii::getPathOfAlias('webroot.images') .  '/'  . '.jpg');
                    }
            $this->redirect(array('view','id'=>$model->addid));
        }
    }

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

whats wrong in the code?? i get confused, unable to solve problem

thank you in advance...

Upvotes: 0

Views: 1242

Answers (1)

Andrii Mishchenko
Andrii Mishchenko

Reputation: 2694

Try this:

if(isset($_POST['Add']))
{
    $model->attributes=$_POST['Add'];
    $model->createtime=date("d m y G:i:s ");
    $model->username=Yii::app()->user->name;
    $model->imageFile=CUploadedFile::getInstance($model,'imageFile');
    if ($model->imageFile) 
    {
        $model->image = uniqid() . '.jpg';
        if (!$model->imageFile->saveAs(Yii::getPathOfAlias('webroot.images') . '/' . $model->image))
            $model->addError('image', 'File saving error');
    }
    if(!$model->hasErrors() && $model->save())
    {
        $this->redirect(array('view','id'=>$model->addid));
    } else {
        // here you can delete saved image if necessary
    }
}

Upvotes: 1

Related Questions