在Yii 1.1.x中无法使用CUploadedFile上传文件

时间:2014-02-14 09:46:21

标签: php file-upload yii frameworks

我正在尝试使用Yii中的CUploadedFile功能上传图像。我的模型中有以下函数 - 错误发生在beforeSave()中。显然,当我检查目录没有文件时,文件由于某种原因没有保存。

这是我收到的错误:

move_uploaded_file(/var/www/myshop/public_html/shopimages/29a80cf8-630f-11e2-9998-14dae9d6777c.jpg) 
[function.move-uploaded-file]: failed to open stream: No such file or directory

我的型号代码如下:

public function beforeValidate()
{
    $this->new_display_image = CUploadedFile::getInstance($this, 'new_display_image');
    return parent::beforeValidate();
}

public function beforeSave()
{   
    if ($this->new_display_image && !$this->hasErrors()) {
        $filename = (($this->isNewRecord && empty($this->Guid)) ? str_replace('.','-',uniqid('', true)) : $this->Guid).'.'.$this->new_display_image->extensionName;
        $display_image = param('productImagePath').$filename;//$this->Guid.'.'.$this->new_display_image->extensionName;
        if ($this->new_display_image->saveAs($display_image)) 
            $this->display_image = basename($display_image);
    }
}

    public function afterSave() 
{
    if($this->isNewRecord)
    {
        extract($this->getAttributes());
        $lastSavedObject = self::model()->findByAttributes(compact('product_name','colour_id','organisation_id'));
        $lastSavedObject->colour_id = 21;

        //Uploaded image if there is any, and replace with GUID.
        if(!empty($display_image))
        {
            $baseUploadDirectory = param('productImagePath');
            $display_image = $baseUploadDirectory . $display_image;
            $correct_display_image = $baseUploadDirectory . $lastSavedObject->Guid.".".pathinfo($display_image, PATHINFO_EXTENSION);

            //For any reason; if product image is removed, misplaced
            if(file_exists($display_image))
            {
                if(rename($display_image, $correct_display_image))
                    $lastSavedObject->display_image = basename($correct_display_image);
            }else{
                $lastSavedObject->display_image = 'placeholder.jpg';
            }

        }else{
            $lastSavedObject->display_image = 'placeholder.jpg';
        }

        $lastSavedObject->save();
        $this->Guid = $lastSavedObject->Guid;
    }

    return parent::afterSave();
}

当我在beforeSave()中使用var_dump $ display_image时,我得到以下对象

object(CUploadedFile)[281]
  private '_name' => string '200.jpg' (length=7)
  private '_tempName' => string 'C:\wamp\tmp\php9207.tmp' (length=23)
  private '_type' => string 'image/jpeg' (length=10)
  private '_size' => int 13959
  private '_error' => int 0
  private '_e' (CComponent) => null
  private '_m' (CComponent) => null

任何人都可以帮助我解决为什么我在beforeSave()函数中出现此错误

1 个答案:

答案 0 :(得分:1)

问题出在$ display_image var中,原因是路径不正确:

        //$display_image = param('productImagePath').$filename;//$this->Guid.'.'.$this->new_display_image->extensionName;

        $display_image = './shopimages/'.$filename;