Wolfer Wolfer - 5 months ago 27
Ajax Question

Symfony 2: File constrains on a AJAX file upload

I have created normal Symfony form. However I require additional files to be uploaded (photos, certificates) which I handle by AJAX and are not retrieved via Symfony form.
Instead file upload is handled in separate controllers actions via file bag.

I would like to limit the maximum file size (only for this action).
If the upload was handled by classic form I would use the file constraint
but this way I do not now how to apply it.

I check mime-type and successful upload by methods on UploadedFile, however the documentation for method for retrieving the size is in a way discouraging (UploadedFile#method_getClientSize).

Is there a way how to use FileValidator/File constraint without the form?

Answer

I have got inspired by actual implementation of FileValidator:

$file = $request->files->get('file');
$path = $file->getPathname();
$size = round(filesize($path) / 1000000, 2);
$limit = (int) $constraint->maxSize;

if ($size > $limit) {
    //Add violation
}

This solution works and is probably better then use getClientSize().