Saving files in blob

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

Save file using blob

After this article 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

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

class Candidate extends CActiveRecord
 	 * Property for receivig the file from the form
	 * It should be different fron any other field in database
	public $uploadedFile;

        public function rules()
            return array(
                array('uploadedFile', 'file', 'types'=>'jpg, gif, png'),

	*saves the name, size ,type and data of the uploaded file
	public function beforeSave()



	return parent::beforeSave();;


Do not forget to give a rule for this attribute, because has to be safe. Is also a good practice to delete any rule refering the other 4 fields (file_name, file_type, file_size, file_content), because they are not supposed to be modified by massively assigned inputs.

Edit the view:

In the view we can put:

<div class="row">
<?php echo $form->labelEx($model,'uploadedFile'); ?>
<?php echo $form->fileField($model,'uploadedFile'); ?>
<?php echo $form->error($model,'uploadedFile'); ?>
Displaying images:

For show the image we can write an action:

	 * Displays the preview of the photo.
	public function actionDisplay()
		header('Content-Type: '.$model->file_type);
		echo $model->file_content;
5 2
Viewed: 60 499 times
Version: Unknown (update)
Category: Tips
Written by: zaccaria
Last updated by: zaccaria
Created on: Nov 3, 2010
Last updated: 7 years ago
Update Article


View all history

Related Articles