Download File From Blob/bytea

Hi everybody,

I follow the great wiki to upload files in my database (I use postgresql), and it works well. Now I would like to download these files, and still regarding from wiki I wrote this function :

  public function actionDownloadFile()




    header('Pragma: public');

    header('Expires: 0');

    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

    header('Content-Transfer-Encoding: binary');

    header('Content-length: '.$model->file_size);

    header('Content-Type: '.$model->file_type);

    header('Content-Disposition: attachment; filename='.$model->file_name);


            /*$myFile = "/tmp/testFile2.txt";

            $fh = fopen($myFile, 'w') or die("can't open file");

            $stringData = "content ".$model->file_content."\n";

            fwrite($fh, $stringData);



        echo $model->file_content;


Browser gets me a file like waited, but whatever the file is, it gets me something of 15 bytes where it is written "ressource id #58". Then, I wrote in a file all data concerning this file (name, size, type, content) and they seem good… except the content… which is equal to "ressource id #58".

So if you have any idea… I tried many things I found on php manual but nothing gave my satisfaction. I also tried the sql statement used by yii in order to know if the problem came from postgresql but it returns well what we wait for. So I think there is something missing in my php functions but I don’t know what… maybe the header ?? or maybe a function to decode/encode the content…

THanks by advance


I know store files in database is bad way but I would like to do it though

I think that you didn’t saved correctly the file, but only the reference.

Check the database field for be sure.

Was your upload form with encoding mutipart?

I checked my database and the content seems well, same for what the statement returns

concerning upload form, I followed exactly the wiki.

  <div class="row">

<?php echo $form->labelEx($model,'uploadedFile'); ?>

<?php echo $form->fileField($model,'uploadedFile'); ?>

<?php echo $form->error($model,'uploadedFile'); ?>


  public function beforeSave()











    return parent::beforeSave();


I still think that in the database you have the wrong data.

Did you try "SELECT file_content FROM file_table", are you sure that there is the correct content?

Also, I don’t know what for are all other parameters, but for me works fine:


I think it’s good content… the hex string in table matches well with the hexdump of file so…

Ok… one solution could be to do it by hand… I mean create his own sql query and treat the result directly in function instead of using yii loadModel()… And I’ll see what will happen

What you are actually receiving is a PHP resource. Try stream_get_contents(resource).

For explanations check:

Hope it helps. Cheers