Difference between #3 and #4 of Saving files to a blob field in the database

changed
Title
Saving files to a blob field in the
databaseblob
unchanged
Category
Tips
changed
Tags
File uploadfile
changed
Content
As a follow-up from the [How to upload aSave 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 to the filesystem, this article will do the same using a
blob field 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 the model:model

The first step is to change the model in order to self manage the file:



~~~
[php]
class Candidate extends CActiveRecord
{
        
	/**
 	 * Property for receivingreceivig the file from the form
	 * It should be different fromfron any other field
in the database
	 */
	public $uploadedFile;

	public        public 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 this attribute as itattribute,
because has to be safe. Is also a good practice to delete any rule
referring 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);
	echo
		echo $model->file_content;
}
	}
~~~