File Upload in Yii For File Upload and Save in Database and in physical folder you can use this code  In View   
beginWidget('CActiveForm', array(
 'id'=>'files-form',
 'enableAjaxValidation'=>false,
        'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
labelEx($model,'filename'); ?>
error($model,'filename'); ?>
endWidget(); ?>
In controller Create Action  public function actionCreate()
    {
        $model=new files;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
                    
        if(isset($_POST['files']))
        {
                   
          $rnd = rand(0,9999); // use to generate random
            $model->attributes=$_POST['files'];
                        $uploadedFile = CUploadedFile::getInstance($model, 'filename');
                        $fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
              
                    $model->filename = $fileName; 
                     $model->size = $uploadedFile->getSize();  //get size of file
                     $model->file_type = $uploadedFile->getType();  //get type of file                      
                       
            if($model->save()){
            $uploadedFile->saveAs(Yii::app()->basePath.'/../uploads/fiels/'.$fileName); // image will uplode to rootDirectory/uploads/fiels/   
                        $this->redirect(array('view','id'=>$model->id));}
                       
        }
        $this->render('create',array(
            'model'=>$model,
        ));
    }
you can use this function to convert file size (Bytes) to KB and MB and store in db  /**
 * This function use to format Size Units
 * @param type $bytes
 * @return string
 */
function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }
        return
}
you can write This function in helpers\Core.php file and can call function using this code $size= Core::formatSizeUnits($size); // $size is file sizeFor File Validation you can use CFileValidator
No comments:
Post a Comment