How to upload a file using a model

Comparing #8 with #9

Revision #9 was created by François Gannaz François Gannaz on May 1, 2012, 9:37:57 PM.

Add links toward the API, add a more usual form syntax (like Gii templates), remove invalid link, insert titles

Content

## 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.
[...]
```

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.
[...]
```

Finally, create the action view and generate a file upload field[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.
 
 
 
```php 
$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
.
[...]
### Links

* [Russian Version](http://dbhelp.ru/form-file-upload/page/)
 
* [Chinese version](http://www.itkuaixun.com/bbs/thread-62-1-1.html)