Revision #4 has been created by Orteko on Nov 3, 2010, 12:49:08 PM with the memo:
Spelling/Grammar fixes, minor code reformatting.
Save file using blob
------------------
After [this articleAs a follow-up from the [How to upload a file using a model](http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/ "How to upload a file using a model")
wiki entry that explains how to save a file
into the filesystem,
here anthis article
forwill do the same using a blob field in
the database.
#### Edit the model
:
The first step is to change the model in order to self manage the file:[...]
class Candidate extends CActiveRecord
{
/**
* Property for receivi
ng the file from the form
* It should be different fro
nm any other field in
the database
*/
public $uploadedFile;
public function rules()
{
return array(
{
return array(
array('uploadedFile', 'file', 'types'=>'jpg, gif, png'),
);
);
}
/**
*
s Saves the name, size
,
type and data of the uploaded file
*/
public function beforeSave()
{
if($file=CUploadedFile::getInstance($this,'uploadedFile'))
{
$this->file_name=$file->name;
$this->file_type=$file->type;
$this->file_size=$file->size;
$this->file_content=file_get_contents($file->tempName);
}
return parent::beforeSave();
;
}
}
```
Do not forget to give a rule for this attribute
, because as it has to be safe. Is also a good practice to delete any rule refer
ring
to the other 4 fields (file_name, file_type, file_size, file_content),
becauseas they are not supposed to be modified by massively assigned inputs.
#### Edit the view:
In the view we can put:[...]
### Displaying images:
ForTo show the image we can write an action:[...]
```php
/**
* Displays the preview of the photo.
*/
public function actionDisplay()
{
$model=$this->loadModel();
header('Content-Type: '.$model->file_type);
echo $model->file_content;
}
```