2

I have a form in which i am passing image in base64 format, now before submitting form i am converting image base64 to uploaded file object , which is working fine but now i want to validate the uploaded file image. How to achieve this. In my build form method i have added validation but its not working. Right now want to restrict image to 2mb but its even allowing more than 2mb image to get uploaded.

     $builder
       ->add('picture', FileType::class, [
            'label' =>  $trans('user.picture.name'),
            'required' => true,
            'constraints' => [
               // new Image(['mimeTypes' => ['image/jpeg']]),
                new File(['maxSize' => '2M', 'mimeTypes' => ['image/jpeg']]),
            ],
        ]);


function onPreSubmit(FormEvent $event)
{

    $form = $event->getForm();
    $data = $event->getData();

    list(, $data['imagebase64']) = explode(',', $data['imagebase64']);

    $filePath = tempnam(sys_get_temp_dir(), 'hijob');
    $image = base64_decode($data['imagebase64']);
    file_put_contents($filePath, $image);

    $photo = new UploadedFile(
        $filePath,
        'photo.jpeg',
        'image/jpeg'
    );

    $data['picture'] = $photo;
    $event->setData($data);

}

1 Answer 1

1

If I understood you want to use Symfony\Component\Validator\Constraints as Assert in Entity class. That should be done something like this.

**
 * @Assert\File(
 *     maxSize = "1024k",
 *     mimeTypes = {...},
 *     mimeTypesMessage = "Please upload a valid ..."
 * )
 */

Check https://symfony.com/doc/current/reference/constraints/File.html

Sign up to request clarification or add additional context in comments.

1 Comment

My form does not have data class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.