Yii Framework Forum: how to display image stored in database - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

how to display image stored in database Rate Topic: -----

#1 User is offline   rama 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 52
  • Joined: 18-February 11
  • Location:india

Posted 18 June 2011 - 01:30 AM

hi all i am trying to store the image path in database and try to show the image on screen

the code if used in controller
public function actionShowimage() {
        $data = Pic::model()->findByPk($_GET['id']);
        echo '<img src="D:\Dev\Apache\htdocs\apartmentf\images\dadmom1.png;base64,' . chunk_split(base64_encode($data->img)) . '" />';
        exit();
        }




in view
public function actionShowimage() {
        $data = Pic::model()->findByPk($_GET['id']);
        echo '<img src="D:\Dev\Apache\htdocs\apartmentf\images\dadmom1.png;base64,' . chunk_split(base64_encode($data->img)) . '" />';
        exit();
        }

Or can i directly extract the path stored in database and give it in src of img tag?
<div class="content">
        <?php
        $source=array();
         $source= Yii::app()->db->createCommand()
			->select('file_name')
			->from('pic')
			->where('id=:id', array(':id'=>$model->id))
			->queryColumn();
           echo '<img src="'.$source.'"/>';

        ?>
 </div>

i have no idea what is correct procedure to do. please help me
0

#2 User is offline   kokomo 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 289
  • Joined: 23-July 10

Posted 18 June 2011 - 04:20 AM

Note: You posted twice your controller code ;)

Of course you should use the file infos from the database cause your first solution with absolute paths D:\... will only work on your local dev machine but not on a hosting environment with a different OS and/or directory structure.

I prefer to save the path and the filename in seperate db fields. It's then easier to display only the filename.

Furthermore, I would suggest you to use / instead of \ directory seperators.
See the following page with further informations about that.

Portable PHP code: DIRECTORY_SEPERATOR is not necessary


Edit:
Sorry, wrote wrong answer to display image from filesystem but you need to display image from blob field in database.

See this wiki: Saving files to a blob field in the database
You need an action like actionDisplaySavedImage() to achieve your goal.

This post has been edited by kokomo: 18 June 2011 - 06:18 AM

0

#3 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 18 June 2011 - 04:57 AM

View Postkokomo, on 18 June 2011 - 04:20 AM, said:

Note: You posted twice your controller code ;)

Of course you should use the file infos from the database cause your first solution with absolute paths D:\... will only work on your local dev machine but not on a hosting environment with a different OS and/or directory structure.

I prefer to save the path and the filename in seperate db fields. It's then easier to display only the filename.

Furthermore, I would suggest you to use / instead of \ directory seperators.
See the following page with further informations about that.

Portable PHP code: DIRECTORY_SEPERATOR is not necessary


Edit:
Sorry, wrote wrong answer to display image from filesystem but you need to display image from blob field in database.

See this wiki: Saving files to a blob field in the database
You need a action like actionDisplaySavedImage() to achieve your goal.

now i tried this code for displaying images form blob field in database
controller code:
  public function actionDisplaySavedImage()
{

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



    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: gif');
    header('Content-Disposition: attachment; filename='.$model->file_name);

        echo $model1->file_name;
}



in _form.php i have did this.
<?php echo CHtml::link('image',array('displaySavedImage','id'=>$model->primaryKey)); ?>



but when i run this it saya undefined index:id
please help me
0

#4 User is offline   PeRoChAk 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 585
  • Joined: 26-November 10
  • Location:Lahore, Pakistan

Posted 18 June 2011 - 05:16 AM

 public function actionDisplaySavedImage()
{

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



    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: gif');
    header('Content-Disposition: attachment; filename='.$model->file_name);

        echo $model1->file_name;
}

Error is in the code
    $model=$this->loadModel($_POST['Pic']['id']);

As we have set the ID in the link section, so, you should do it as
    $model=$this->loadModel($_GET['id']);

Cheers
Perochak
Web Design - Logo Design - Application Development

My Blog | Forums Comparison
0

#5 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 18 June 2011 - 05:40 AM

View PostPeRoChAk, on 18 June 2011 - 05:16 AM, said:

 public function actionDisplaySavedImage()
{

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



    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: gif');
    header('Content-Disposition: attachment; filename='.$model->file_name);

        echo $model1->file_name;
}

Error is in the code
    $model=$this->loadModel($_POST['Pic']['id']);

As we have set the ID in the link section, so, you should do it as
    $model=$this->loadModel($_GET['id']);


I tried even with that but i didnt get it.i got the same error.Do i have to mention any source attribute for it.
please help me.I think there is some problem with controller code.
0

#6 User is offline   PeRoChAk 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 585
  • Joined: 26-November 10
  • Location:Lahore, Pakistan

Posted 18 June 2011 - 05:49 AM

<?php echo CHtml::link('image',array('NameofControlloer/displaySavedImage','id'=>$model->primaryKey)); ?>

Replace
NameofControlloer with your controller
Cheers
Perochak
Web Design - Logo Design - Application Development

My Blog | Forums Comparison
0

#7 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 18 June 2011 - 06:18 AM

View PostPeRoChAk, on 18 June 2011 - 05:49 AM, said:

<?php echo CHtml::link('image',array('NameofControlloer/displaySavedImage','id'=>$model->primaryKey)); ?>

Replace
NameofControlloer with your controller

I am able to call function in the controller but it tells
undefined index:id

is it not getting posted.please guide me through that code:
0

#8 User is offline   kokomo 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 289
  • Joined: 23-July 10

Posted 18 June 2011 - 06:47 AM

Do a
print_r($_GET);

in the controller to see what values are set.
0

#9 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 18 June 2011 - 08:54 AM

View Postkokomo, on 18 June 2011 - 06:47 AM, said:

Do a
print_r($_GET);

in the controller to see what values are set.

am i in the right path of displaying the image from database into view?
0

#10 User is offline   PeRoChAk 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 585
  • Joined: 26-November 10
  • Location:Lahore, Pakistan

Posted 18 June 2011 - 07:54 PM

You should post your code over here

Model, Controller & View where you want to display the image
Cheers
Perochak
Web Design - Logo Design - Application Development

My Blog | Forums Comparison
0

#11 User is online   jacmoe 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 2,697
  • Joined: 10-October 10
  • Location:Denmark

Posted 18 June 2011 - 08:01 PM

@Nalajala:
It's really annoying that you don't post any code!! >:(

How are we supposed to help you out when we have nothing to go on?

Could you please post the code for the action you have problems with?

And maybe the view too?

Thanks. ;)
"Less noise - more signal"
0

#12 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 20 June 2011 - 12:02 AM

View Postjacmoe, on 18 June 2011 - 08:01 PM, said:

@Nalajala:
It's really annoying that you don't post any code!! >:(

How are we supposed to help you out when we have nothing to go on?

Could you please post the code for the action you have problems with?

And maybe the view too?

Thanks. ;)

hi jacmoe

i have been trying to display the image in view from my mysql database.fields i have in my database are
id(primary key)
image
file_name
file_type
file_size
file_content

i am able to upload my image to database but i am not able to display it in my view.I wrote the following action in my controller
  public function actionDisplaySavedImage()
{
              

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


    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: png');
    header('Content-Disposition: attachment; filename='.$model->file_name);

        echo $model->file_name;
}



in my _form.php
i created a link
<?php echo CHtml::link('my_link_name',array('displaySavedImage','id'=>$model->primaryKey)); ?>


when i click the link in browser it prompts an error
undefined index:id

please help me

thanks
0

#13 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 20 June 2011 - 12:38 AM

View Postkokomo, on 18 June 2011 - 06:47 AM, said:

Do a
print_r($_GET);

in the controller to see what values are set.

when i do print_r($_GET) i seen an empty array
0

#14 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 20 June 2011 - 01:10 AM

View Postnalajala, on 20 June 2011 - 12:38 AM, said:

when i do print_r($_GET) i seen an empty array

do i have to modify any code in _form.php for my link now.

<?php echo CHtml::link('my_link_name',array('displaySavedImage','id'=>$model->primaryKey)); ?>

should i replace this code and is my controller code in the right way,because when i do a print_r($_GET) i see an empty array

please help me
0

#15 User is offline   kokomo 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 289
  • Joined: 23-July 10

Posted 20 June 2011 - 01:56 AM

To be sure the image display logic work replace the $_GET['id'] with a hardcoded primary key which is available in your database.
  $model=$this->loadmodel(1); // replace 1 with an existing row in your db

Then try if you see the image.

Quote

in my _form.php
i created a link
<?php echo CHtml::link('my_link_name',array('displaySavedImage','id'=>$model->primaryKey)); ?>


when i click the link in browser it prompts an error
undefined index:id

please help me

thanks

So, the error says undefined index:id which for me is a indication for that you don't pass correctly the $model to the view (e.g _form.php).
The fact that the $_GET output is empty fortified my suspicion.

Please post the complete action's that are displaying the views which are not working. Also post the renderPartial part of the view which is loading the _form.php. Maybe you pass the $model to the view which call renderPartial('_form') but don't pass the $model also to the _form.php view so there it is not available which would explain the error message.

And please use code tags ([code ] [ /code] without spaces) to post code cause it is much more readable, thanks.

Also try to learn to debug errors better by yourself (do print_r's for different var's and look at the values; replace variables with hardcoded values to see if it works in principle; try to debug the code using breakpoints with your IDE e.g netbeans,...). I bet it is a really simple bug in your code which you normally should find by yourself at the latest after our hints here in the forum.

This post has been edited by kokomo: 20 June 2011 - 01:58 AM

0

#16 User is offline   rama 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 52
  • Joined: 18-February 11
  • Location:india

Posted 20 June 2011 - 02:22 AM

View Postkokomo, on 20 June 2011 - 01:56 AM, said:

To be sure the image display logic work replace the $_GET['id'] with a hardcoded primary key which is available in your database.
  $model=$this->loadmodel(1); // replace 1 with an existing row in your db

Then try if you see the image.


So, the error says undefined index:id which for me is a indication for that you don't pass correctly the $model to the view (e.g _form.php).
The fact that the $_GET output is empty fortified my suspicion.

Please post the complete action's that are displaying the views which are not working. Also post the renderPartial part of the view which is loading the _form.php. Maybe you pass the $model to the view which call renderPartial('_form') but don't pass the $model also to the _form.php view so there it is not available which would explain the error message.

And please use code tags ([code ] [ /code] without spaces) to post code cause it is much more readable, thanks.

Also try to learn to debug errors better by yourself (do print_r's for different var's and look at the values; replace variables with hardcoded values to see if it works in principle; try to debug the code using breakpoints with your IDE e.g netbeans,...). I bet it is a really simple bug in your code which you normally should find by yourself at the latest after our hints here in the forum.

when i tried with the
$model=$this->loadmodel(1);

it says webpage not found
No webpage was found for the web address: http://localhost/apa...playSavedImage/
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.

my controller code:
<?php

class PicController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','displaySavedImage'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Pic;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Pic']))
		{

			$model->attributes=$_POST['Pic'];
            $model->image=CUploadedFile::getInstance($model,'image');
			if($model->save())
				$this->redirect(array('view','id'=>$model->id)
                                				);


		}

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

      	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Pic']))
		{
			$model->attributes=$_POST['Pic'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

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

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

        public function beforeSave()
    {
        if($file=CUploadedFile::getInstance($this,'image'))
        {
            $this->file_name=$file->name;
            $this->file_type=$file->type;
            $this->file_size=$file->size;
            $this->file_content=file_get_contents($file->tempName);
        }

    return parent::beforeSave();
    }
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Pic');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Pic('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Pic']))
			$model->attributes=$_GET['Pic'];

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


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Pic::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
    public function actionDisplaySavedImage()
{
    $model=$this->loadModel(1);

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

        echo $model->file_content;
}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='pic-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


_form.php
<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'pic-form',
	'enableAjaxValidation'=>true,
	'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo $form->labelEx($model,'image'); ?>
        <?php echo CHtml::activeFileField($model, 'image'); ?>
		<?php echo $form->error($model,'image'); ?>
	</div>
      <?php echo CHtml::link('my_link_name',array('displaySavedImage','id'=>$model->primaryKey)); ?>

<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->

0

#17 User is offline   smug 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 73
  • Joined: 29-April 11

Posted 20 June 2011 - 02:41 AM

ok instead id if i give 1 there a file is getting downloaded of the given content type and when i say

echo $model->image
society.gif(text format) is being displayed.this society.gif is in my database
where am i going wrong

help me
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users