YII文件上传不起作用

时间:2014-01-07 11:05:24

标签: php yii

您好我正在尝试上传文件并使用YII将其写入数据库,但一切都没有发生,它既不保存文件也不保存名称保存到数据库。

我的观点......

<div class="row">
        <div class="span4"><?php echo $form->labelEx($model,'slider_image'); ?></div>
        <div class="span5"><?php echo $form->fileField($model,'slider_image'); ?></div>
        <div class="span3"><?php echo $form->error($model,'slider_image'); ?></div>
</div>

我的验证模型......

    public function rules()
{

    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        //more rules
        array('slider_image', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true),
        //more rules
    );
}

控制器:

    public function actionEdit()
{

    $id = Yii::app()->getRequest()->getQuery('id');

    $model = CustomPage::model()->findByPk($id);
    if (!($model instanceof CustomPage))
    {
        Yii::app()->user->setFlash('error',"Invalid Custom Page");
        $this->redirect($this->createUrl("custompage/index"));

    }
    if(isset($_POST['CustomPage']))
    {

        $model->attributes = $_POST['CustomPage'];

        if (CUploadedFile::getInstance($model,'slider_image')) {

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

        }


        if ($model->validate())
        {
            if ($model->deleteMe)
            {
                $model->delete();
                Yii::app()->user->setFlash('info',"Custom page has been deleted");
                $this->redirect($this->createUrl("custompage/index"));
            }
            else {
                $model->request_url =  _xls_seo_url($model->title);
                if (!$model->save())
                    Yii::app()->user->setFlash('error',print_r($model->getErrors(),true));
                else
                {
                    if (CUploadedFile::getInstance($model,'slider_image'))  {
                    $model->slider_image->saveAs(Yii::app()->baseUrl.'images/'.$model->slider_image);
                    }

                    Yii::app()->user->setFlash('success',
                        Yii::t('admin','Custom page updated on {time}.',array('{time}'=>date("d F, Y  h:i:sa"))));
                    $this->beforeAction('edit'); //In case we renamed one and we want to update menu

                }
            }
        }

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

}

我在die;之后尝试if (CUploadedFile::getInstance($model,'slider_image'))并且没有任何事情发生,所以它似乎根本没有认识到它。

谢谢。

1 个答案:

答案 0 :(得分:2)

我认为你在视图中遗漏了一条小指令

检查以确认您的表单标记具有属性“enctype”

即。 <form action="" method="post" enctype="multipart/form-data">...</form>

要在CActiveForm中进行设置,请执行:

<?php $form = $this->widget('CActiveForm', array(
        'htmlOptions'=>array('enctype'=>'multipart/form-data')
));?>