Reputation: 951
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.
Upvotes: 3
Views: 1428
Reputation: 1769
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.
Upvotes: 3