changed
Title
Saving filesto a blob fieldinthe databaseblob
Saving filesto a blob fieldinthe databaseblob
File uploadfile
As a follow-up from the [How to upload aSave file usinga 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 to the filesystem, this article will do the same using ablobfield in the database.------------------###After [this article](http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/ "How to upload a file using a model") that explains how to save a file in the filesystem, here an article for do the same using a blob field in database. #### Edit themodel:model The first step is to change the model in order to self manage the file: ~~~ [php] class Candidate extends CActiveRecord { /** * Property forreceivingreceivig the file from the form * It should be differentfromfron any other field inthedatabase */ public $uploadedFile;publicpublic function rules(){ return{ return array(array('uploadedFile',array('uploadedFile', 'file', 'types'=>'jpg, gif, png'),); }); } /*** Saves*saves the name,size, typesize ,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); }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();} return parent::beforeSave();; } ~~~ Do not forget to give a rule for thisattribute as itattribute, because has to be safe. Is also a good practice to delete any rulereferring torefering the other 4 fields (file_name, file_type, file_size, file_content),asbecause they are not supposed to be modified by massively assigned inputs.####### Edit the view: In the view we can put: ~~~ [php] <div class="row"> <?php echo $form->labelEx($model,'uploadedFile'); ?> <?php echo $form->fileField($model,'uploadedFile'); ?> <?php echo $form->error($model,'uploadedFile'); ?> </div> ~~~ ### Displaying images:ToFor show the image we can write an action: ~~~ [php]/** */** * Displays the preview of the photo.*/ public*/ public function actionDisplay(){ $model=$this->loadModel(); header('Content-Type:{ $model=$this->loadModel(); header('Content-Type: '.$model->file_type);echoecho $model->file_content;}} ~~~