Show Pdf File From Database

I have a PDF file saved in a blob field in mysql database. But now I do not know how to open it or offer it do download it from view. There is many how-to’s for images, but I did not find any for other file types. Anyone have any idea, how to do it?

I’ve tried with CDetailView, but there is no type designed to work with pdf files. $model->Priloga is the database blob field where pdf is saved.


<?php $this->widget('zii.widgets.CDetailView', array(

	'data'=>$model,

	'attributes'=>array(

		'idPoseg',

		'Datum',

		'Strosek',

		'Opomba',

		array(

		'label'=>'Priloga',

		'type'=>'raw',

		'value'=>$model->Priloga,

		),

		'idKatPoseg',

		'Inventarna',

		'idServiser',

		'idUporabnik',

		'CasVpisa',

	),

)); ?>

Hi,

first u can try in your view file


array(

		    'name'=>'venue_floor_image',

                    'type'=>'html',

		    'value'=>'(!empty($data["venue_floor_image"])) ? 

                                Venue::model()->gridFloorData($data["venue_floor_image"])

                            : 

                                CHtml::tag("img",array("height"=>\''.$height.'\',\'width\'=>\''.$width.'\',"src" => UtilityHtml::getAdminImage(GxHtml::valueEx($data,\'venue_floor_image\'),\''.$path1.'\'))

                            )',

		),	


public function gridFloorData($image)

        {

            $height = SystemConfig::getValue('venue_profile_height');

            $width = SystemConfig::getValue('venue_profile_width');

            $path='/upload/venue_profile/';

            $path1='/upload/venue_floor/';

            

            $image_path =  UtilityHtml::getAdminImage($image,$path1);

            

            $userfile_array = explode(".", strtolower($image_path));

            $userfile_extn = ($userfile_array[count($userfile_array) - 1] );

            

            if ($userfile_extn == 'jpg' || $userfile_extn == 'png' || $userfile_extn == 'jpeg' || $userfile_extn == 'gif' || $userfile_extn == 'bmp' || $userfile_extn == '') {

                echo $data = '<a class="fancybox1" href="'.$image_path.'"><img height='.$height.' width='.$width.' src="'.$image_path.'"></a>';

            }else{

             //if file is PDF........

                echo $data = '<a target="_blank" href="'.$image_path.'">'.$image.'</a>';

            }

        }

		


public static function getAdminImage($image,$path) {


		if ($image != '' && file_exists(YiiBase::getPathOfAlias('webroot') . $path . $image)) {

			return  Yii::app()->request->baseUrl . $path . $image;

		} else {

			return  Yii::app()->request->baseUrl . $path.'images.jpg';

		}


	}



Hope it will be helpful

This is for an image. What about PDF file? Is this working for PDF too? I guess not, because I do not have any size data in database. Only blob field where file is.

Hi

if u can store the PDF file in folder so just simple u can add path

I do not have it in folder. I saved it in database:


	public function beforeSave()

	{

		if($file=CUploadedFile::getInstance($this,'uploadedFile'))

		{

			$this->Priloga=file_get_contents($file->tempName);

		}

		return parent::beforeSave();

	}

And then saved model normally. Now I can not read file from database.

Hi

if u save only PDF file name it’s not read about any thing so best way is u can simply save the pdf file in images folder. it’s easy to maintain

just like /locahost/test/demo.pdf

If I understand correctly this WIKI I am saving the file into the database. Am I wrong? If I try to save file to folder I need to rewrite the whole save procedure.

Have you tried accessing your pdf like it’s described in a wiki you linked? Function actionDisplaySavedImage() seems reasonable. Just create link to this action with id of pdf as a parameter.

Hi,

no it’s not wrong on http://www.yiiframework.com/wiki/95/saving-files-to-a-blob-field-in-the-database/ it’s just save in db instruction (How to insert a file in db) but if u can open PDF u must be insert the folder

try this


      $path =YiiBase::getPathOfAlias('webroot');

					$url ='http://'.$_SERVER['HTTP_HOST']. Yii::app()->baseUrl;

					$model->image=$_FILES['Coupon']['name']['image'];

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

					$model->image->saveAs($path.'/upload/coupon/'.$model->image);

					$image_path=$url.'/upload/coupon/'.$model->image;

					$model->image_url=$image_path;

                                         $model->save(false);

I’ve tried to do that, but the only thing I manage to get out of it is a plain text of PDF. I can not get the PDF file.

VIEW:


array(

		'name'=>'Priloga',

		'value'=>CHtml::link('Poglej PDF',array('displayPDF','id'=>$model->idPoseg)),

		'type'=>'raw',

		),

CONTROLLER:


	public function actionDisplayPDF($id)

	{

		$model=$this->loadModel($_GET['id']);

		echo $model->Priloga;

	}

Ankit Modi where do I put this? That is for file upload if I understand correctly? That means that I do not save files to database, but to a folder on server?

first u insert the pdf file name in your db and this pdf save in folder so u can both of must compulsory

I’ve lost you. :(

I need to save only your part of code or do I still need my part when I save tempName to database?

That’s because you didn’t follow the tutorial. You can’t just echo file content like that, and expect browser to automagically recognize what to do with it :). You have to send headers first. Just like in a tutorial:


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);

If you always want to display pdf, then it’s not necessary to store it’s type in a db. Second header may look like this:


header('Content-Type: application/pdf');

Hahahah, how stupid of me. :D

Thank you, sidewinder. That is working like a charm now. Loving it.

Trying to do the same thing in CGridView, but nothing shows up whatever I do:


<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'poseg-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'Inventarna',

		'inventarna.Naziv',		

		//'idPoseg',

		'Datum',

		'idKatPoseg',

		'idKatPoseg0.Naziv',

		'Strosek',

		'Opomba',

		array(

			'name'=>'Priloga',

			'type'=>'html',

			'value'=>(!empty($model->Priloga))?CHtml::link('Poglej PDF',array('displayPDF','id'=>$model->idPoseg)):'Ni priloge!',

		),

		'idServiser',

		'idServiser0.Naziv',

		'inventarna.NRedni',

		//'idUporabnik',

		//'CasVpisa',

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>


'value'=>(!empty($model->Priloga))?CHtml::link('Poglej PDF',array('displayPDF','id'=>$model->idPoseg)):'Ni priloge!'

Value has to be either a valid php callback or a string which can be evaluated. You can enclose your statement in a lambda expression, or simply put quotes around :).

That should work (I put double quotes only to avoid escaping single quotes) .


'value'=>'(!empty($model->Priloga))?CHtml::link("Poglej  PDF",array("displayPDF","id"=>$model->idPoseg)):"Ni  priloge!" '  

If you want to know why analyse this:

http://www.yiiframew…mn#value-detail

and this:

http://www.yiiframew…pression-detail

While this solution works (at least it should :) ), the correct way of putting links in CGridView is using CLinkColumn and setting correct expressions for label and url.

I’ve tryed the first solution but I could not fix it to work.

Then I tryed the second one and everything is working but the urlExpression. I am aware that it is not logical to put $data->Priloga into urlExpression, but I do not know what is the right thing to put in.




array(

			'class'=>'CLinkColumn',

			'header'=>'Priloga',

			'labelExpression'=>'(!empty($data->Priloga))?"Poglej PDF":"Ni priloge"',

			'urlExpression'=>'array("displayPDF","id"=>$data->Priloga)',

		),

Is it the problem, that I can not use the same action for CLinkColumn that I did for CDetailView?


public function actionDisplayPDF($id)

	{

		$model=$this->loadModel($_GET['id']);

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

		header('Content-Type: application/pdf');

		echo $model->Priloga;

	}

What exactly is a problem now? Are links showing up in a column? Does yii throw any exception?

Both solutions should work. Action actionDisplayPDF can be used anywhere in your application. Maybe there is a problem with creation of url? Do you have routing rules set correctly?

Looks like I just need to write the problem up here and I find the solution.

I was trying to get Priloga field into the ID and that was wrong. When I inserted the idPoseg field it started to work.


array(

			'class'=>'CLinkColumn',

			'header'=>'Priloga',

			'labelExpression'=>'(!empty($data->Priloga))?"Poglej PDF":"Ni priloge"',

			'urlExpression'=>'array("displayPDF","id"=>$data->idPoseg)',

		),

I still need to learn a lot. And to think differently