CHtml FileField

Using CHtml class we are creating fileField in yii framework. This post will help you to understand about how to upload file in different method, how to get and save the uploaded file in controller, file validation in model yii framework.

DONT FORGET multipart/form-data

<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'files-form',
 'htmlOptions'=>array('enctype' => 'multipart/form-data'),
)); ?>

Syntax

public static string activeFileField(CModel $model, 
                                string $attribute, 
                                array $htmlOptions=array ( ))
[OR]
public static string fileField(string $name, 
                                string $value='', 
                                array $htmlOptions=array ( ))
                                

$model      - the data model
$attribute  - the attribute
$htmlOptions- additional HTML attributes
{return}	- the generated input field

activeFileField With CHtml

Generate input file field using activeFileField function with model details

<?php echo  CHtml::activeFileField($model,'file_image'); ?>

fileField With Form

Generate input file field using fileField with form, model details

<?php echo  $form->fileField($model,'file_image'); ?>

fileField With CHtml (Without Model Name)

Generate input file field using fileFile without model details

<?php echo  CHtml::fileField('LoginForm[file_image]'); ?>

OUTPUT HTML

<input type="file" id="LoginForm_file_image" name="LoginForm[file_image]" value="" />

File In Controller

Using CUploadedFile::getInstance method, We can get the uploaded file in controller. Using saveAs($directory_with_filename) method, we can save the posted file. Yii have the magic method to get the file size, file extension name and more.

 public function actionFile()
 {
    .............
    $filemodel=new Files;  
    if(isset($_POST['Files']))
    {
         $model->attributes=$_POST['Files'];
         if($model->file_image=CUploadedFile::getInstance($model,'file_image')) {
            $file_size=$model->file_image->size;
            $file_extension=$model->file_image->extensionName;
            //127.0.0.1/filemanager/images/test.jpg
            $model->file_image->saveAs(Yii::app()->basePath."/../images/test.jpg");
         }  
    }
    .............
    .............
}

File Validation In Model

All Rules and validation in Yii Model