Saving Image in DB using CUploadedFile

I followed the Yii wiki example at http://www.yiiframework.com/wiki/2 . It works perfectly when saving the image to a path. I then tried to save it to Db using the following code:





public function actionCreate()

	{

		$model=new Images;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Images']))

		{

			$model->attributes=$_POST['Images'];

			$model->file_data=CUploadedFile::getInstance($model,'file_data');

			if(!$model->file_data->getHasError()) {

				$model->filename=$model->file_data->getName(); 

				$model->mime_type=$model->file_data->getType();

				$model->file_size=$model->file_data->getSize();

			}

			if($model->save())

				$this->redirect(array('view','id'=>$model->image_id));

		}

		$this->render('create',array(

			'model'=>$model,

		));

	}



The file is uploaded to Db but in a corrupted form. I can read back the original file. Suspecting my db structure, I upload the same file by using the simple PHP upload() function. It uploaded perfectly. And I noticed the blob reading were different i.e:

  1. for upload() – file_data(BLOB - 31.2Kib)

  2. for CUploadedFile – file_data(BLOB - 14B)

Same code saves the file perfectly into a path but not to a db. Is there any other setting for CUploadedFile if saving in DB

Take a look at this tutorial.

Thanks @[size="2"][color="#1C2837"]zaccaria. I had missed out on file_get_contents(). Now it works fine. The correct code is:[/color][/size][size="2"] [/size]

[size="2"] [/size]

[size="2"][color="#1C2837"]




public function actionCreate()

	{

		$model=new Images;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Images']))

		{

			$model->attributes=$_POST['Images'];

			$file=CUploadedFile::getInstance($model,'file_data');

			if(!$file->getHasError()) {

				$model->filename=$file->getName(); 

				$model->mime_type=$file->getType();

				$model->file_size=$file->getSize();

				$model->file_data=file_get_contents($file->tempName);

			}

			if($model->save())

				//$model->file_data->saveAs(Yii::app()->getBasePath() . '/../images/dbImages/' . '1.jpg');

				$this->redirect(array('view','id'=>$model->image_id));

		}

		$this->render('create',array(

			'model'=>$model,

		));

	}

[/color][/size]