article

Saturday, March 22, 2014

Upload file in yiiframework

Upload file in yiiframework


Create table t_users
 id_user varchar(30)
profile_picture varchar(100)
name varchar(50)

Form
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'tuser-form',
 'enableAjaxValidation'=>false,
 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>
<p class="note">
 Fields with <span class="required">*</span> are required.
</p>
 
<?php echo $form->errorSummary($model); ?>
 <div class="row">
  <?php echo $form->labelEx($model,'profile_picture'); ?>
  <?php echo $form->fileField($model,'profile_picture',array('size'=>60,'maxlength'=>200)); ?>
  <?php echo $form->error($model,'title'); ?>
 </div>
 
Controller 
$model->attributes=$_POST['TUser'];
 $model->profile_picture=CUploadedFile::getInstance($model, 'profile_picture');
 if($model->save()){
  if(strlen($model->profile_picture)>0)
   $model->profile_picture->saveAs(Yii::app()->basePath.'/../upload/'.$model->profile_picture);
  $this->redirect(array('view','id'=>$model->id_user));
 }
 
 filter files use the rules in your model
 public function rules()
    {
        return array(
            array('picture_profile', 'file', 'types'=>'jpg, gif, png'),
           ...
        );
    }

Related Post