Uploading & Downloading files to/from Database


I am new to yii. I have requirement to upload a file to database & then download it from database. I have browsed topics where they talk about uploading file to server using CUploadedFile.

Can anyone please let me know if I can save uploaded file to the database instead of saving on the server file system. Are there any APIs for this in Yii?

User should also be able to download the file from the database.

Any help would be greatly appreciated.



May be, you need a blob datatype.


$file = /path/to/yourtmpfile;

$fp = fopen($file, 'rb');

$binary_data = fread($fp, filesize($file))

insert $binary_data to database;


$binary_data = read from database blob field; 

$fp = fopen($filename, 'wb');

fwrtie($fp, $binary_data);

download refer header() funciton;


[poor english]

Thanks for the reply. Is there a ready API for this in Yii Framework.

You don’t need any api.

you have simply to creata a blob fild in your table and save the data in it.

For example, assuming you have a table called foo with a blob field called binary_data:

$foo=new Foo;



The variable $binary_data can be filled with CUploadedFile.

For serve this data to the user, you can do an action download, for instance, like that:

public function actionDownload()



		header('Content-Type: image/jpeg');

		echo $model->data;


Thanks for your inputs. Shall try this.