phpyiiimage-uploadingyii-cactiverecordyii-cformmodel

Uploading image to with custom name in Yii framework


I am trying to upload images from registration form in Yii framework. The image will be saved in "img/avatar" folder and the name of the image should be changed to the username. The piece of code I use for this is below:

//uploading avatar to the img/avatar folder
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$personModel->picture = $upload_file;
$picture_name = $userModel->username;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
    $upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name);
}
$personModel->save();
//end of image uploading part

The problem is: the name of the username has been saved in picture row of the database. But the image was not uploaded to the folder. I am trying to find out the problem in the code. but cannot solve it. Any suggestions?


Solution

  • The problem has been solved through following code:

    $uploadFile = CUploadedFile::getInstance($personModel, 'picture');
    $extension = pathinfo($uploadFile, PATHINFO_EXTENSION);
    $fileName = $userModel->username . '.' . $extension;
    
    if (isset($uploadFile)) {
        $personModel->picture = $fileName;
        $uploadFile->saveAs(Yii::app()->basePath . '/../img/avatar/' . $fileName);
    }