Upload Image

I’ve created a file upload form and i’ve written the validation rules to handle the image, when I select the image and save the image in a correct way all is ok, but when i choose upload the image in a wrong way (eg exceeding the maximum allowed size image) my web application dose not show the error message in the corresponding view, however the rule complies with the validation of the maximum of the image and not allow the image loading.

The issue is that i have to show the error message, how can i do it?

View:




<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>

<?php 


echo CHtml::activeFileField($model, 'imagenurl'); ?>

	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>

<?php echo CHtml::endForm(); ?>



Controller:




public function actionUpdateimg()

	{

	$model=$this->loadModel();

	        	$theTime = date("dmy"); 


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

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

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

			$myfile=CUploadedFile::getInstance($model,'imagenurl');

			if (is_object($myfile) && get_class($myfile)==='CUploadedFile')


			$model->imagenurl=$model->idProducto.'_'.$theTime.'_'.$myfile->name;

			

			if($model->save())

//			$model->imagenurl->saveAs('../images/'.$model->idProducto.'_'. $model->imagenurl);

			if (is_object($myfile))

			$myfile->saveAs('../images/'.$model->imagenurl);

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

		}

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

			'model'=>$model,

		));

	}



Model:





public $imagenurl;   

//	 $imagenurl= $imagenurl;

	public function rules()

	{

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

		// will receive user inputs. 

		return array( 

			array('Descripcion', 'length', 'max'=>200),     

			array('Marca, Clase', 'length', 'max'=>100), 

			array('Tamano, Carac', 'length', 'max'=>45), 

			array('Carac', 'required'),/* valida campo requerido*/

			array('imagenurl', 'file', 'allowEmpty'=>true, 'types'=>'jpg,gif', 'maxSize'=>409600,'tooLarge'=>'The file was larger than 400K. Please upload a smaller file.'), 

			array('idProducto, Descripcion, Marca, Clase, Tamano', 'safe', 'on'=>'search'),

		);

	}



NOTE: moved topic to proper forum

To display the error you need to use the error() method - http://www.yiiframew…ml#error-detail

May I suggest XUpload extension for your uploads? :D

Thumbs up if you like it :)

I’m new in yii, i’ve tried to implement the error() method, but i have not found the correct way to implement it, do you have an example to use the method in my code ?

This should work


<?php echo CHtml::error($model, 'imagenurl'); ?>

i have written your advice,but it has not worked, the page dose not show the error menssage




<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>

<?php 

echo CHtml::error($model, 'imagenurl');

echo CHtml::activeFileField($model, 'imagenurl'); ?>

        <div class="row buttons">

<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

        </div>

<?php echo CHtml::endForm(); ?>



I am having a similar issue, only its with not displaying an error for incorrect file extensions. It seems to me like the framework does not pass the errors variable properly when dealing with the “File” validator. Because the validation is done after the form is submitted (has to or the file wouldn’t be there for the validator to be able to examine it). When the page reloads its after the form has been submitted, since the form was already submitted there isn’t a way for it to check if that field validated. Shouldn’t the validation success or failure be passed via GET or POST?

Or am I missing something ???

Figured it out

Make sure that the max file size you are setting ‘409600’ is not greater than the max file size set in your php.ini file.

I have just noticed that if you attempt to upload a file that is greater than the allowed file upload based on your php settings the file validator will not return ANY error messages. So make sure you set your maxSize to the same, or less than you upload_max_filesize in the php.ini file.

Also it is easier to set your file size if you do this:

for 40 megabytes instead of : 41943040 put in 1024102440

works for everything and makes it easier to tell what the size limit is :D

I have reviewed my php.ini and i have found the maxsize: upload_max_filesize = 2M (therefore it is not problem, thanks for the advice).

I have the same problem in all validations (eg, maxsize, incorrect file extension, etc), I can’t display the error

Its a bug in the framework, I just tested it. Even if you set your maxSize to LESS than your upload_max_filesize you will still run into issues if you attempt to upload a file larger than your upload_max_filesize.

If you are testing with a file that is larger than 2M than your errors will not show up due to this bug.

The only workaround is to set your upload_max_filesize to a ridiculous amount such as 100M.

thank you very much for the replies, I hope to find another way, I’ll keep trying

I made ​​it work, I managed to show validation errors (allowEmpty, types, maxSize, etc.) apparently the only thing missing was to place the brackets around "if" inside the controller

View:




<div class="form">


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

	'id'=>'producto-form',

	'enableAjaxValidation'=>false,

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

)); 


?>

	<?php echo CHtml::error($model, 'imagen_url');  ?>


	<div class="row" id="imagen_url">

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

		<?php echo CHtml::activeFileField($model, 'imagen_url'); ?>

	</div>

 	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>

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

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



Controller:




public function actionUpdateimg($id)

	{

	$model=$this->loadModel($id);


	        	$theTime = date("YmdHi"); 

		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

    		$model->scenario = 'imagen_url';

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


			$myfile=CUploadedFile::getInstance($model,'imagen_url');


			if (is_object($myfile) && get_class($myfile)==='CUploadedFile')

			$model->imagen_url=$model->id_publicacion.'_'.$theTime.'_'.$myfile->name;

    		if($model->save())


			if (is_object($myfile)){

						$folder='images/publicaciones/';

						if(!is_dir($folder.$model->id_publicacion)){

        									mkdir($folder.$model->id_publicacion);

										}

			$myfile->saveAs('images/publicaciones/'.$model->id_publicacion.'/'.$model->imagen_url);

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

			}

		}

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

			'model'=>$model,

		));

	}




Model:





public function rules()

        {

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

                // will receive user inputs. 

                return array( 

  array('id_proveedor, titulo, descripcion', 'required'),    

//			array('fecha_registro', 'disabled'),    

			array('id_proveedor', 'numerical', 'integerOnly'=>true),    

			array('imagen_url', 'length', 'max'=>100),   

			array('titulo', 'length', 'max'=>50),

			array('descripcion', 'length', 'max'=>150), 

                        array('imagen_url', 'file', 'on'=>'imagen_url','allowEmpty'=>false, 'types'=>'jpg,gif', 'maxSize'=>1024*400,'tooLarge'=>'The file was larger than 400K. Please upload a smaller file.'), 

                        array('id_publicacion, id_proveedor, titulo, descripcion, imagen_url, fecha_registro', 'safe', 'on'=>'search'),

                );

        }



I hope to help you in the upload image issues, about validation problems.