Morgan Millet
Morgan Millet

Reputation: 89

How to upload files in Symfony 3

I followed this doc to add an Upload File on my form (see image).

My form works and if I add a file in it (I have for example '47f1f107e3e9629a8f41a861ccf1737a.png') in my database. My problem now is I can't display this image.

Bestiaire.php :

/**
 * @ORM\Column(type="string")
 *
 * @Assert\NotBlank(message="Please, upload the bestiaire brochure as a PDF file.")
 * @Assert\File(mimeTypes={ "image/png" })
 */
private $brochure;

public function getBrochure()
{
    return $this->brochure;
}

public function setBrochure($brochure)
{
    $this->brochure = $brochure;

    return $this;
}

BestiaireType.php

    <?php

    namespace Tolkien\BestiaireBundle\Form;

    use Symfony\Bridge\Doctrine\Form\Type\EntityType;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
    use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
    use Symfony\Component\Form\Extension\Core\Type\SubmitType;
    use Symfony\Component\Form\Extension\Core\Type\TextareaType;
    use Symfony\Component\Form\Extension\Core\Type\TextType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\Form\FormEvent;
    use Symfony\Component\Form\FormEvents;
    use Symfony\Component\OptionsResolver\OptionsResolver;
    use Symfony\Component\Form\Extension\Core\Type\FileType;


    class BestiaireType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('date',                   DateTimeType::class)
                ->add('name',                   TextType::class)
                //etc..
                ->add('brochure',               FileType::class, array('label' => 'Brochure (PDF file)'))
                ->add('save',                   SubmitType::class);


            $builder->addEventListener(
                FormEvents::PRE_SET_DATA,  
                function(FormEvent $event) {
                    $bestiaire = $event->getData();

                    if (null === $bestiaire) {
                        return;
                    }
                }
            );
        }
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'Tolkien\BestiaireBundle\Entity\Bestiaire'
            ));
        }
    }
In my form : 

    {{ form_row(form.brochure) }}

My controller :
/**
 * @Security("has_role('ROLE_AUTEUR') or has_role('ROLE_USER') or has_role('ROLE_ADMIN') ")
 */
public function addAction(Request $request)
{
    $bestiaire = new Bestiaire();
    $form = $this->get('form.factory')->create(BestiaireType::class, $bestiaire);



    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
        /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
        $file = $bestiaire->getBrochure();

        $fileName = md5(uniqid()) . '.' . $file->guessExtension();

        $file->move(
            $this->getParameter('brochures_directory'),
            $fileName
        );

        $bestiaire->setBrochure($fileName);

        $em = $this->getDoctrine()->getManager();
        $em->persist($bestiaire);
        $em->flush();

        $request->getSession()->getFlashBag()->add('notice', 'Annonce bien enregistrée.');

        return $this->redirectToRoute('tolkien_bestiaire_view', array('id' => $bestiaire->getId()));
    }
    return $this->render('TolkienBestiaireBundle:bestiaire:add.html.twig', array(
        'form' => $form->createView(),
    ));

}

Config.yml :

parameters:
    locale: fr
    brochures_directory: '%kernel.root_dir%/web/uploads/brochures'

My vews :

<li><img src="{{ asset('uploads/brochures/' ~ bestiaire.brochure) }}"/></li>

Upvotes: 0

Views: 4724

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

You have incorrect brochures_directory_ value:

'%kernel.root_dir%/web/uploads/brochures'

kernel.root_dir is /app/ folder, therefore you need to add /../ after to get to project root.

'%kernel.root_dir%/../web/uploads/brochures'

And that's how it looks in the guide that you're following.

Upvotes: 3

Related Questions