Studi kasus :
– Nama File yang diupload akan disimpan di field pada database. ex: dashboard_image (varchar 255)
– File akan diupload ke folder yang telah ditentukan.

* _form.php (View : TblDashboard)



beginWidget('CActiveForm', array(
'id'=>'tbl-dashboard-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>




<div class="row">
<?php echo $form->labelEx($model,'dashboard_image'); ?>
<?php echo CHtml::activeFileField($model, 'dashboard_image'); ?>
<?php echo $form->error($model,'dashboard_image'); ?>
</div>

* Controller (TblDashboard)
public function actionCreate()



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


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


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


$uploadedFile = CUploadedFile::getInstance($model,'dashboard_image');
$fileImage = "{$uploadedFile}"; //  file name

//Simpan nama file ke field dashboard_image
$model->dashboard_image = $fileImage;


if($model->save())
{
// image will uplode to rootDirectory/images/maps/
if (!empty($uploadedFile))

 $uploadedFile->saveAs(Yii::app()->basePath.'/../images/maps/'.$fileImage);
$this->redirect(array('view','id'=>$model->dashboard_code));
}
}

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


Lakukan hal yang sama untuk controller actionUpdate(). Kondisi upload akan dilakukan apabila ada image yang dipilih.

Controller (TblDashboard)
public function actionDelete()



public function actionDelete($id)
{
unlink(Yii::app()->basePath.'/../images/maps/'.TblDashboard::model()->find('dashboard_code=:dashboard_code', array(':dashboard_code'=>$id))->dashboard_image);


$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}


Note :
– Pastikan “file uploads” pada PHP setting anda diaktifkan.
– Yii::app()->basePath (Path Root aplikasi Yii).
– Code diatas belum diberikan kondisi bila tidak memilih image.

Sumber : http://www.yiiframework.com/wiki/349/how-to-upload-image-photo-and-path-entry-in-database-with-update-functionality/