How to upload a file using a model

You are viewing revision #10 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#9)next (#11) »

  1. The Model
  2. The Controller
  3. The View

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'),
		);
	}
}

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).

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));
	}
}

[CUploadedFile::saveAs()] in one of the methods of [CUploadedFile]. You can also access directly to the file through its "tempName" property.

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();

Another syntax is to use static calls in [CHtml] instead of [CActiveForm]. The result is the same as above.

<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>
...
<?php echo CHtml::activeFileField($model, 'image'); ?>
...
<?php echo CHtml::endForm(); ?>
Links
66 4
64 followers
Viewed: 519 750 times
Version: Unknown (update)
Category: Tutorials
Written by: qiang
Last updated by: samdark
Created on: Feb 4, 2009
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles