How to validate file upload field

Hello,

How to validate the file upload field in yii…

The uploaded image is save id in folder not in db.

Did you check CFileValidator? You can add validation to your model like this:


array('image', 'file', 'allowEmpty'=>true, 'types'=>'jpg,jpeg,gif,png')

1 Like

For validation File

Just Add

public function rules()

{


    return array(


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


    );


}

For validation

hi friend you can also validate your upload image by creating a function in controller

like

public function imageValidate($img, $maxwidth = 1024, $maxheight = 1024)

{





	$imagehw = getimagesize($img);


	$imagewidth = $imagehw[0];


	$imageheight = $imagehw[1];


	$imagetype = $imagehw[2];


	$valid_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);


	if (in_array($imagetype, $valid_types))


	{


		if($imagewidth < $maxwidth || $imageheight < $maxheight )


			return 1;


	}





	return 0;


}

and checked it in your model by passing the value.

Rajesh: Don’t do stuff like that in the controller, it doesn’t belong there as it should know as little as possible of what your model/form needs to work.

You can easily call a custom validation function by using a validation rule like

[size="2"]


array('attribute', 'myFunctionName');

[/size]

It will call the function in the model during validation. You can do that verification either there, or create some sort of file-helper component and call that.

It’s a lot cleaner.

How can i validate only image extension without page load. when a image upload it will check immediate whether it is match with extension or not. user will get a message instantly. i do it by that way:::::

array(‘image’,‘file’,‘types’=>“jpg,gif,png”,‘message’=>‘Invalid’),

but it work only after page load…i want it will check instantly when upload…plz explain with example…

How can i validate only image extension without page load. when a image upload it will check immediate whether it is match with extension or not. user will get a message instantly. i do it by that way:::::

Quote

array(‘image’,‘file’,‘types’=>“jpg,gif,png”,‘message’=>‘Invalid’),

but it work only after page load…i want it will check instantly when upload…plz explain with example…

how to get the original name of the image to store in database??

i am using


if($model->save())

			{

				if($model->image !== null)

                        {

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

							$model->image = uniqid() . '.jpg';

                            $image->saveAs( Yii::getPathOfAlias('webroot.images') .  '/'  . '.jpg');

                        }

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

			}

by this it takes the original name in the database but assigns the unique id generated name to the stored image in webroot/image folder

whats wrong in this case??