Set Mime_type validation in Symfony

Posted by Ngu Soon Hui on Stack Overflow See other posts from Stack Overflow or by Ngu Soon Hui
Published on 2009-03-27T08:30:37Z Indexed on 2010/05/04 14:38 UTC
Read the original article Hit count: 225

Filed under:

I want to make sure that during file upload time, only the file of the format jpeg, png and gif are allowed. So the "File of type:" below in the screenshot must show jpeg, png and gif:

I did the following for my validator in Symfony:

$this->setValidator ( 'upload your filehere',
	 new sfValidatorFile ( array (
	 'required'=>true,
	 'mime_types' => array ('image/jpeg, image/png, image/gif' )
	  ) ,
	  array(

	  'mime_types'=> 'only jpeg'
	  )
	  ) 
	  );

but when I click on the upload button, the files are not filtered accordingly; what did I do wrong?

I also try

$this->setValidator ( 'upload your filehere',
	 new sfValidatorFile ( array (
	 'required'=>true,
	 'mime_types' => 'image/jpeg, image/png, image/gif' 
	  ) ,
	  array(

	  'mime_types'=> 'only jpeg'
	  )
	  ) 
	  );

But it doesn't work, too.

I tried the following in my form class, but unfortunately it doesn't work as well:

<?php

class UploadCaseForm extends sfForm {
    public function configure() {
    	$this->setWidgets ( array ('Documents' => new sfWidgetFormInputFile ( ) ) );
    	$this->widgetSchema->setNameFormat ( 'UploadCase[%s]' );


    	$this->validatorSchema ['Documents'] = new sfValidatorFile ( 
    	array ('mime_types' => 'web_images' ), 
    	array ('invalid' => 'Invalid file.',
    	 'required' => 'Select a file to upload.', 
    	 'mime_types' => 'The file must be of JPEG, PNG or GIF format.' ) );

    }
}
?>

Here's the action code:

	public function executeIndex(sfWebRequest $request) {
		$this->form = new UploadCaseForm ( );

if ($this->getRequest ()->getMethod () == sfRequest::POST) {
		var_dump($request->getParameter('UploadCase'));


	}

}

Edit: The accepted answer is the answer, as far as the server side validation goes. If anyone wants a client side validation, i.e., filtering the type of file that can be uploaded even before the operation hits server, then maybe there is no reliable way to do it, because of browser's constraint.

© Stack Overflow or respective owner

Related posts about symfony