Reputation: 61
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);
}
Upvotes: 2
Views: 374
Reputation: 390
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
Upvotes: 1