Symfony2 filesize constraint in form

Viewed 1379

I am trying to add filesize constraint to my form in order to prohibit users to upload files larger than 2M (as set in my php.ini) and I tried the following: In the formBuilder:

->add('avatar', 'file', array( 
            'label'  => 'Insert foto',
            'required' => false,
            'constraints'=> array(
                new File(array('maxSize'=>'2048k',
                'maxSizeMessage'=>'More than 2MB!!'))),
            'label_attr'   =>  array(
                'class' => 'control-label'
            ),
            'attr'   =>  array(
                'class'           => 'form-control filestyle',
                'placeholder'     => 'Foto'... etc,

Also I added file property to my main entity class

    /**
 * @Assert\File(
 *     maxSize = "2048k",
 *     mimeTypes = {"image/png"},
 *     mimeTypesMessage = "Please upload a valid PNG file",
 *     maxSizeMessage = "Upload not more than 2M size files"
 * )
 */
protected $avatar;

In my controller I get the file with this:

$file = $form['avatar']->getData();

but still all the manipulations are done only AFTER the file is actually uploaded to my server. I dont want to upload it if it is larger than 2MB, instead I want to display an error message. Maybe I should use Formevents but no working example was found. Any ideas would be helpful. Thank You.

1 Answers
Related