The Model ¶
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.class Item extends CActiveRecord { public $image; // ... other attributes public function rules() { return array( array('image', 'file', 'types'=>'jpg, gif, png'), ); } }
The Controller ¶
Then, in the controller class define an action method to render the form and collect user-submitted data.
class ItemController extends CController { public function actionCreate() { $model=new Item; if(isset($_POST['Item'])) { $model->attributes=$_POST['Item']; $model->image=CUploadedFile::getInstance($model,'image'); if($model->save()) { $model->image->saveAs('path/to/localFile'); // redirect to success page } } $this->render('create', array('model'=>$model)); } }
The View
Finally, create the action view and generate a file upload field.
$form = $this->beginWidget( 'CActiveForm', array( 'id' => 'upload-form', 'enableAjaxValidation' => false, 'htmlOptions' => array('enctype' => 'multipart/form-data'), ) ); // ... echo $form->labelEx($model, 'image'); echo $form->fileField($model, 'image'); echo $form->error($model, 'image'); // ... $this->endWidget();
No comments:
Post a Comment