参考:http://sunnycoolboy.i.sohu.com/blog/view/179686775.htm
1、函数原型:
public static string activeFileField(CModel$model,string $attribute, array $htmlOptions=array ( ))
2、调用例子:
(1)首先,设置form,这一步一 定要做,把form设置为’multipart/form-data’,具体请看我的:
)); ?>
_form.php
<!--图片上传-->
<div class="row">
<?php echo $form->labelEx($model,'Images'); ?>
<?php /* echo $form->textField($model,'Images',array('size'=>60,'maxlength'=>255)); */ ?>
<?php
echo "<input type='hidden' value='".$model->downloadurl."'";//把值传过去 修改字段时不加这句会丢失,
echo CHtml::activeFileField($model,'Images'); ?> <!--调用控件-->
<?php echo $form->error($model,'Images'); ?>
</div>
(3) 如果你想预览图片,那么请注意了,可以加上这么一段:
<div class=”row”>
</div>
controller.php
public function actionCreate()
{
$model=new Trafficevent;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Trafficevent']))
{
$_POST['Trafficevent']['Endtime'] = strtotime($_POST['Trafficevent']['Endtime']);
$model->attributes=$_POST['Trafficevent'];
//var_dump($_POST['Trafficevent']);
//图片上传
$image=CUploadedFile::getInstance($model,'Images');
if(isset($image->extensionName)){
$url=time().".".$image->extensionName;
$imageurl = substr(Yii::app()->request->hostInfo.Yii::app()->homeUrl,0,-9)."images/trafficevent/".$url;
$model->Images=$imageurl;
$image->saveAs("./images/trafficevent/".$url);
}
//$_POST['Trafficevent']['Images'] = $haha;
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
models:
array('Images', 'file','allowEmpty'=>true,'types'=>'jpg, gif, png',
'maxSize'=>1024 * 1024 * 1, // 1MB
'tooLarge'=>'图片须小于 1 MB.',
),