Upload File In Database


I have been trying to upload a file to database since 10days but failing each time.

I have tried 2methods:

  1. upload the actual file to DB.

  2. store the path only.

I am pretty sure that the second method should be preferred, I have gone thru many forums but could not find any.

Any help would be of great use to me.

Hi shravya.

I have just posted today the solution to second method: "store the path only", please see this message in the next post Image Upload Using Ajax.

I hope this will help you.

hi shrav,ya, its better to save path in DB, and sotre file in some folder insiide your Web app.

your model will be like this…

class Item extends CActiveRecord { 	public $image; 	// ... other attributes   	public function rules()	


     	return array(  	

   	array('image', 'file', 'types'=>'jpg, gif, png'),	


   } }

try your controller like…

class ItemController extends CController { 

	public function actionCreate() 	


	$model=new Item;     	if(isset($_POST['Item'])) 	

	{         	$model->attributes=$_POST['Item'];         	$model->image=CUploadedFile::getInstance($model,'image');  	


      	{             	$model->image->saveAs('path/to/localFile'); 	// redirect to success page  	

   	}     	}  

   	$this->render('create', array('model'=>$model)); 


and finally view file like…

$form = $this->beginWidget( 	'CActiveForm',  

   array(     	'id' => 'upload-form',     	'enableAjaxValidation' => false,     	'htmlOptions' => array('enctype' => 'multipart/form-data'), 	) ); // ... echo $form->labelEx($model, 'image');

 echo $form->fileField($model, 'image');

 echo $form->error($model, 'image'); 

// ... echo CHtml::submitButton('Submit'); $this->endWidget();

I hope it will help you


I have tried the above method, but when I upload the file and say create, it says that the field is empty.

this is my code–


array(‘name’, ‘file’, ‘types’=>‘jpg, gif, png’),



&#036;form = &#036;this-&gt;beginWidget('CActiveForm',  


	'id' =&gt; 'upload-form',          

	'enableAjaxValidation' =&gt; false,

        'htmlOptions' =&gt; array('enctype' =&gt; 'multipart/form-data'),   



 echo &#036;form-&gt;fileField(&#036;model, 'name');

 echo &#036;form-&gt;error(&#036;model, 'name'); 


&lt;?php &#036;this-&gt;endWidget(); ?&gt;


public function actionCreate()


	&#036;model=new Event;



	// Uncomment the following line if AJAX validation is needed

	 &#036;this-&gt;performAjaxValidation(&#036;model);// AJAX VALIDATION


















I have noticed that my view file has a widget in a widget. Would that create a problem?

Hi all,

I have got the solution…there was some problem with nested widgets…

but I’m unable to give the path in the controller.

I gave something like this which is not working. PLz help


Try this

$uploadfile= $model->name;

$uploadfile->saveAs(dirname(Yii::app()->basePath) . '/attachments/'.$uploadfile);  

Thank you,

it worked!!