Uploading image to with custom name in Yii framework

234 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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);
}
0
On

Well first thing you need to do is to prevent database input if the picture is not saved.

if(isset($uploadedfile))
{
      if($upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name)
      {
                 $personModel->save();                
      }
      else
      {
           //throw error
      }
}

As far as problems in the code go. Most common problem is directories not existing, path to them not being correct.

0
On
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$ext = pathinfo($upload_file->picture, PATHINFO_EXTENSION);
$picture_name = $userModel->username . '.' . $ext;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
    $upload_file->saveAs('/Your_correct_path/.../etc/'.$picture_name);
}
$personModel->save();
0
On
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$picture_name = $userModel->username . '.' . pathinfo($upload_file, PATHINFO_EXTENSION);
$personModel->picture = $picture_name;
if (isset($upload_file)) {
    $upload_file->saveAs(Yii::app()->basePath . '/../img/avatar/' . $picture_name);
}
$personModel->save();

You have to check your folder permission.