Yii Framework - upload a file using a model


SUBMITTED BY: Guest

DATE: May 19, 2013, 1:08 p.m.

FORMAT: PHP

SIZE: 2.4 kB

HITS: 869

  1. The Model
  2. First declare an attribute to store the file name in the model class (either a form model or an active record model). Also declare a file validation rule for this attribute to ensure a file is uploaded with specific extension name.
  3. class Item extends CActiveRecord
  4. {
  5. public $image;
  6. // ... other attributes
  7. public function rules()
  8. {
  9. return array(
  10. array('image', 'file', 'types'=>'jpg, gif, png'),
  11. );
  12. }
  13. }
  14. You can add others validation parameters as described in CFileValidator. For instance, one can add a "maxSize" restriction (the PHP ini settings will of course prevail).
  15. The Controller
  16. Then, in the controller class define an action method to render the form and collect user-submitted data.
  17. class ItemController extends CController
  18. {
  19. public function actionCreate()
  20. {
  21. $model=new Item;
  22. if(isset($_POST['Item']))
  23. {
  24. $model->attributes=$_POST['Item'];
  25. $model->image=CUploadedFile::getInstance($model,'image');
  26. if($model->save())
  27. {
  28. $model->image->saveAs('path/to/localFile');
  29. // redirect to success page
  30. }
  31. }
  32. $this->render('create', array('model'=>$model));
  33. }
  34. }
  35. CUploadedFile::saveAs() in one of the methods of CUploadedFile. You can also access directly to the file through its "tempName" property.
  36. The View
  37. Finally, create the action view and generate a file upload field.
  38. $form = $this->beginWidget(
  39. 'CActiveForm',
  40. array(
  41. 'id' => 'upload-form',
  42. 'enableAjaxValidation' => false,
  43. 'htmlOptions' => array('enctype' => 'multipart/form-data'),
  44. )
  45. );
  46. // ...
  47. echo $form->labelEx($model, 'image');
  48. echo $form->fileField($model, 'image');
  49. echo $form->error($model, 'image');
  50. // ...
  51. $this->endWidget();
  52. Another syntax is to use static calls in CHtml instead of CActiveForm. The result is the same as above.
  53. <?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>
  54. ...
  55. <?php echo CHtml::activeFileField($model, 'image'); ?>
  56. ...
  57. <?php echo CHtml::endForm(); ?>

comments powered by Disqus