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

changed
Title
Saving files into a blob field in the database
unchanged
Category
Tips
changed
Tags
fileFile upload
changed
Content
SaveAs 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 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 modelmodel:

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



~~~
[php]
class Candidate extends CActiveRecord
{
        
	/**
 	 * Property for receivigreceiving the file from the form
	 * It should be different fronfrom 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,
becauseattribute as it has to be safe. Is also a good practice
to delete any rule referingreferring 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:



~~~
[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:

ForTo 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;
	}
}
~~~