Yii中的图片上传

时间:2014-02-26 06:45:13

标签: twitter-bootstrap yii

我在Yii框架中实现了图像文件上传。它正在上传图像并成功存储到数据库中,但图像不会存储在我的目录中。在我的控制器中,我添加了以下代码:

public function actionCreate()
{
    $model=new Friends;

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

    if(isset($_POST['Friends']))
    {
        $model->attributes=$_POST['Friends'];

                 $image=CUploadedFile::getInstance($model,'profile_image');
             if (is_object($image) && get_class($image)==='CUploadedFile') 
                {
                  $model->profile_image=$image->name;    
                }
                if($model->save())
            if(is_object($image))
            $image->saveAs(dirname(__FILE__).'/../../friends_picture/'.$model->profile_image);   

        $this->redirect(array('view','id'=>$model->id));
    }

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


错误在哪里?给定的目录名是否正确?

2 个答案:

答案 0 :(得分:3)

试试这段代码。

public function actionCreate()
{
    $model=new Friends;

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

    if(isset($_POST['Friends']))
    {
        $model->attributes=$_POST['Friends'];

        $model->profile_image = CUploadedFile::getInstance($model,'profile_image');

        if($model->save())

            $fullImgSource = Yii::getPathOfAlias('webroot').'/friends_picture/'.$model->profile_image;
            $model->profile_image->saveAs($fullImgSource);


        $this->redirect(array('view','id'=>$model->id));
    }

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

可以帮助你。

由于

答案 1 :(得分:0)

试试这个

$ model-> profile_image = CUploadedFile :: getInstance($ model,'profile_image');

    if($model->save())

        $fullImgSource = Yii::getPathOfAlias('webroot').'/friends_picture/'.$model->profile_image;
        $model->profile_image->saveAs($fullImgSource);