3

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.

Jack
  • 857
  • 14
  • 39
  • Javascript or alike approach will work, but not a bullet-proof solution since javascript could be easily disabled or altered. Better to validate server-side, if you still want on javascript check this out http://stackoverflow.com/questions/8212041/it-is-possible-to-validate-the-size-and-type-of-input-file-in-html5 – Muhammed Mar 17 '16 at 16:54

1 Answers1

3

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.

Community
  • 1
  • 1
Egg
  • 1,782
  • 1
  • 12
  • 28
  • Thank you, I will keep your advice, but now I would find out if there is a more like 'Symfony way' to do that. In addition, as far as I understand JS client validation is not favoured, e.g. in order to be on the safe side we need to make all valdations on server side. Or maybe I am mistakened.. – Jack Mar 17 '16 at 17:08
  • Best to let Symfony do that; as you are doing with `maxSize` and `->add('avatar', 'file')` in your formType. [This post](http://stackoverflow.com/questions/17951294/symfony2-file-upload-step-by-step) should help you. – Egg Mar 17 '16 at 17:18