-1

Is there an easy way to handle user profile image?

I tried with VichUploaderBundle without success.

  • 1
    Show what you've tried (implementation) and where you get stuck. To improve your question just read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) and update your question accordingly. – gp_sflover Apr 12 '17 at 14:10
  • Sure, i follow [installation procedure](https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/installation.md) without any issue and i wanted to use the [yml mapping](https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/mapping/yaml.md). This not have effect to doctrine:schema:update. If is necessary i can attach my configurations – Fabiano Roberto Apr 12 '17 at 14:18
  • 1
    Yes, add your code to see how you implemented it – Francesco Donzello Apr 12 '17 at 14:25

1 Answers1

0

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>