Models (model)
First you need a file upload model:fileupload.php
<?phpClassFileUploadextends cformmodel {public $image; /** * @return array validation rules for model attributes. */public function rules () {return array (//note you wont need a safe rule here array ( ' image ', ' file ', ' allowempty ' = true, ' types ' = ' jpg, JPEG, GIF, PNG '),); } }
Note:> For more validation rules, see Reference:model Rules validation
Array for CForm
The following creates an array for CForm: uploadform.php
<?phpReturnArray' Title ' =' Upload your image ',' Attributes ' =Array' Enctype ' = ' elements ' = array ( ' image ' = array ( ' type ' = ' file ', "), ' buttons ' = > array ( ' reset ' = array ( Span class= "hljs-string" > ' type ' = ' reset ', ' label ' = Span class= "hljs-string" > ' Reset ', " ' submit ' = array ( Span class= "hljs-string" > ' type ' = ' submit ', ' label ' = Span class= "hljs-string", "Upload",),),
Views file (View)
Create view file: upload.php
<?phpif (Yii::app ()->user->hasflash (' Success ')):?> <divclass= "info" > <?php echo yii::app ()->< Span class= "Hljs-title" >user->getflash (' success ');?> </div><? PHP ENDIF;?> <h1>Image upload</h1> <div class= "form" ><? PHP echo $form;? ></div>
Controllers (Controller)
Add Controller and Action (action):
<?phpClassFileuploadcontrollerExtendsCcontroller {PublicfunctionActionupload() {$model =New FileUpload ();$form =New CForm (' Application.views.fileUpload.uploadForm ',$model);if ($form->submitted (' Submit ') && $form->validate ()) { $form->model->image = cuploadedfile::getinstance ( $form->model, ' image '); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //do something with your image here //!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!! Yii::app ()->user->setflash ( ' success ', ' File uploaded ') ; $this->redirect (array ( Upload ')); } $this->render ( ' upload ', Array ( ' form ' + $form));}
The best way to do this here is to perform some action on the picture in your FileUpload model. Note: You do not need to assign a value to fileupload::image , but you can provide a way to access it to achieve the robust model simplification controller.
Reproduced from HDR
Yii uploads files using the Cform class (Form builder)