0

我正在尝试从 Yii 框架中的注册表单上传图像。图像将保存在“img/avatar”文件夹中,图像名称应更改为用户名。我用于此的一段代码如下:

//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

问题是:用户名的名称已经保存在数据库的图片行中。但是图像没有上传到文件夹中。我试图找出代码中的问题。但无法解决。有什么建议么?

4

4 回答 4

0
$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();

您必须检查您的文件夹权限。

于 2016-03-10T18:51:55.227 回答
0
$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();
于 2016-03-10T18:48:02.860 回答
0

该问题已通过以下代码解决:

$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);
}
于 2018-05-28T10:16:47.450 回答
0

那么你需要做的第一件事就是在图片没有保存的情况下防止数据库输入。

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

就代码中的问题而言。最常见的问题是目录不存在,它们的路径不正确。

于 2016-03-10T18:31:49.447 回答