using CUploadedFile and accessing the name of the file

So I am still a newbie to this framework and I stuck on something and I can’t figure it out.

I am trying to upload an image and I use:

$file = CUploadedFile::getInstance($model,‘image’);

to get the instance of the uploaded image. After that I need to get the name of the file but this does not work:

$name = $file->getName();

This script gives me the following error:

Fatal error: Call to a member function getName() on a non-object in /opt/lampp/htdocs/protected/controllers/PlaceController.php

I think maybe it is quite simple to get the name of the file, but I need some help to do it.

I think you have $file === null. Check if your form is using enctype="multipart/form-data".

samdark thank you for the advise. I added enctype=“multipart/form-data” but still it is not working :(

Did you follow the exact advise here?

http://www.yiiframework.com/doc/cookbook/2/

Could it be, you didn’t specify a rule for your image attribute in your scenario (a.k.a. made your file attribute “safe”)?

Mike I am using this tutorial to guide me what to do and I followed every step but still it is not working.

The only difference is that I am using CActiveForm to display the form and my script is not generated with CHtml but looks like that:

<?php echo $form->labelEx($model,‘image’); ?>

<?php echo $form->fileField($model,‘image’); ?>

<?php echo $form->error($model,‘image’); ?>

I have specified the rule in my model:

array(‘image’, ‘file’, ‘types’ => ‘jpg, gif, png’)

Can you check the content of $_FILES (e.g. print_r($_FILES); ) in the upload action?

It would be easier to help you… if you post your code… (using the [ code] [ /code] directive for styling)…

of the model rules, controller action and view…

A friend helped me to fix it. Thank you guys that you tried to help me, I appreciate it.

Could you share your wisdom, please :D. Others might learn from your issue …

i would like to know how?

this is my upload controller

public function actionUpdate($id)

{


	&#036;model=&#036;this-&gt;loadModel(&#036;id);





	// Uncomment the following line if AJAX validation is needed


	// &#036;this-&gt;performAjaxValidation(&#036;model);





	if(isset(&#036;_POST['Nacional']))


	{


		&#036;model-&gt;attributes=&#036;_POST['Nacional'];


		&#036;file_image = CUploadedFile::getInstance(&#036;model,'foto');


		if ( (is_object(&#036;file_image) &amp;&amp; get_class(&#036;file_image)==='CUploadedFile'))


		&#036;model-&gt;foto = &#036;file_image;





		if(&#036;model-&gt;save())


			if (is_object(&#036;file_image))


				&#036;model-&gt;foto-&gt;saveAs(Yii::app()-&gt;basePath.'/&#46;&#46;/images/'.&#036;model-&gt;foto);





			//&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;id_nacional));


	}





	&#036;this-&gt;render('update',array(


		'model'=&gt;&#036;model,


	));


}

the rules of my model

public function rules()

{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


		array('entidad, cargo, nombres, apellidos, email, sexo, cedula, fecha_nacimiento, foto, llenado_por', 'required'),


		array('sexo, usuario_a', 'numerical', 'integerOnly'=&gt;true),


		array('num_confirmacion', 'length', 'max'=&gt;20),


		array('entidad, cargo, email, conyuge, llenado_por', 'length', 'max'=&gt;75),


		array('nombres, apellidos, control_ip', 'length', 'max'=&gt;50),


		array('cedula', 'length', 'max'=&gt;25),


		array('foto', 'length', 'max'=&gt;100),


		array('foto', 'unsafe'),


		array('foto','file','types'=&gt;'jpg, jpeg, png, gif','maxSize'=&gt;1024*1024*0.5, // 0.5MB


        	'tooLarge'=&gt;'The file was larger than 500 KB. Please upload a smaller file.'),


		array('fecha_nacimiento, control_i', 'safe'),


		// The following rule is used by search().


		// Please remove those attributes that should not be searched.


		array('id_nacional, num_confirmacion, entidad, cargo, nombres, apellidos, email, conyuge, sexo, cedula, fecha_nacimiento, foto, llenado_por, control_i, control, control_ip, usuario_a', 'safe', 'on'=&gt;'search'),


	);


}

and my view

&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'foto'); ?&gt;


	&lt;?php echo CHtml::activeFileField(&#036;model, 'foto');?&gt;

<!-- <?php echo $form->fileField($model, ‘foto’, array(‘id_nacional’=>‘foto’)); ?>–>

	&lt;?php echo &#036;form-&gt;error(&#036;model,'foto'); ?&gt;


&lt;/div&gt;

I commented the part of fileField and change it for CHtml::activeFileField because CHtml::activeFileField is the one to work with CUploadedFile::getInstance($model,‘foto’); according the manual of yii frameworl

but i still get no value of the CUploadedFile::getInstance($model,‘foto’); :frowning:

Well I could kill you right now, why dont you post a solution if you found it :)

I need answer to this problem since I’m having it my self right now.

I just had these symptoms too. In my case PHP was configured with file_uploads off. I turned it on and restarted the webserver. Maybe that helps someone.

I got some errors in File Uploading.

" Call to a member function saveAs() on a non-object"

$file = CUploadedFile::getInstance($model,‘cos_sec_prompt’);

$model->cos_sec_prompt->saveAs(Yii::app()->basePath.’/../images/’.$model->cos_sec_prompt);

Thanks in advance!!!

[size="6"]your form[/size]


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'social-form',

	// Please note: When you enable ajax validation, make sure the corresponding

	// controller action is handling ajax validation correctly.

	// There is a call to performAjaxValidation() commented in generated controller code.

	// See class documentation of CActiveForm for details on this.

        'htmlOptions'=>array('class'=>'form-horizontal','enctype' => 'multipart/form-data'),

	'enableAjaxValidation'=>true,

)); ?>


<div class="form-group">

		<?php echo $form->labelEx($model,'social_icon',array('class'=>"col-sm-4 col-md-4 control-label")); ?>

            <div class="col-sm-8 col-md-8">

		<?php echo $form->fileField($model,'social_icon',array('size'=>60,'maxlength'=>255)); ?>

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

            <?php echo $form->hiddenField($model,'social_icon',array('class'=>'form-control',)); ?>

                

            

                 <?php if($model->social_icon!="") { ?>

                 <img src="<?php echo Yii::app()->request->baseUrl."/upload/social_image/thumb/".$model->social_icon; ?>" style="width: 100px; height: 100px; background-color:#858282;" >

                 <?php } ?>

            </div>

	</div>



[size="6"]your model[/size]


public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

                  

                        

                        //array('social_icon', 'file', 'types'=>'jpg, gif, png'), 

                     array('social_icon', 'file','types'=>'jpg,png,gif', 'on'=>'insert'),

                        array('social_icon', 'file', 'types'=>'jpg,png,gif', 'allowEmpty'=>true, 'on'=>'update'),

                    

			

			// The following rule is used by search().

			// @todo Please remove those attributes that should not be searched.

			array('social_id, social_name, social_url, social_icon, social_enabled, social_deleted, social_created_date, social_updated_date', 'safe', 'on'=>'search'),

		);

	}

[size="6"]your controller[/size]


public function actionCreate()

	{

		$model=new Social;

                $model->scenario = 'insert';

               //$model->setScenario('update');


		// Uncomment the following line if AJAX validation is needed

		$this->performAjaxValidation($model);


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

		{

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

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

                                                                                                 

                        if($model->save())

                        {

                            $model->social_icon->saveAs('upload/social_image/'.$model->social_icon);

                            $image = new EasyImage(Yii::app()->basePath.'/../upload/social_image/'.$model->social_icon);

                            $image->resize(254,163);

                            $image->save(Yii::app()->basePath.'/../upload/social_image/thumb/'.$model->social_icon);

                            $this->redirect(array('index'));

                            

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

                        }

		}


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

			'model'=>$model,

		));

	}