╃巡洋艦㊣ 2011-03-07 15:05:27 8502次浏览 4条回复 5 1 0

First declare an attribute to store the file name in the model class (either a form model or an active record model). Also declare a file validation rule for this attribute to ensure a file is uploaded with specific extension name.

class Item extends CActiveRecord
{
    public $image;
    // ... other attributes
 
    public function rules()
    {
        return array(
            array('image', 'file', 'types'=>'jpg, gif, png'),
        );
    }
}

Then, in the controller class define an action method to render the form and collect user-submitted data.

class ItemController extends CController
{
    public function actionCreate()
    {
        $model=new Item;
        if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->save())
            {
                $model->image->saveAs('path/to/localFile');
                // redirect to success page
            }
        }
        $this->render('create', array('model'=>$model));
    }
}

Finally, create the action view and generate a file upload field.

<?php 
    echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); 
?>
...
<?php 
    echo CHtml::activeFileField($model, 'image'); 
?>
...
<?php 
    echo CHtml::endForm(); 
?>

转自cookbook的帖子

觉得很赞
  • 回复于 2011-11-18 17:03 举报

    先收藏。。。。。。

  • 回复于 2012-03-05 23:31 举报

    试了一下这个方法,确实可行。
    path/to/localFile 这个路径有点不清楚,比如我如何去获取原文件名?或者获取原文件的后缀名,这样我才好构造新的文件路径啊?求解

  • 回复于 2012-03-05 23:37 举报

    补充一下上面那个问题,我现在获取原文件名,是用下面这个代码获取:
    $sourceName = $_FILES['Item']['name']['image'];

  • 回复于 2014-03-05 17:04 举报

    已收藏,感谢

您需要登录后才可以回复。登录 | 立即注册