Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 filesize constraint in form

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.

like image 254
Jack Avatar asked Dec 14 '25 02:12

Jack


1 Answers

If you want to check filesizes before the file is uploaded, then you'll need to take a JavaScript approach.

PHP (and Symfony) are server side and can only deal with uploaded files after they have been uploaded. JavaScript is client side and can check files before they are uploaded.

I would put up with it being uploaded and check it as you are at the moment; it's the most reliable approach.

like image 89
Egg Avatar answered Dec 15 '25 14:12

Egg