Is there an easy way to handle user profile image?
I tried with VichUploaderBundle without success.
Is there an easy way to handle user profile image?
I tried with VichUploaderBundle without success.
Save them in your folder with a unique name and store names in the database.
To upload an image you can use a FileType field in your form, documented here. You can use ImageType for form validation as I remember and here is some code which will save the file in a folder and save the filename in the database:
$user = new User();
$form = $this->createForm(UserForm::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$img = $user->getPhoto();
$fileName = md5(uniqid()).'.'.$img->guessExtension();
$user->setPhoto($fileName);
// Move the file to the directory where brochures are stored
$img->move(
$this->getParameter('user_image_directory'),
$fileName
);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
And when you want to display the img you display it in twig in a similar fashion, first you read the filename with $user->getPhoto() and send it to your template, i had some bug when I called user.getPhoto() from the template, maybe it was just me:
img src="{{ asset('media/users/') }}{{ filename }}"></div>