2

I just made a file upload form in my project, thanks to Symfony documentation. My project is in version 2.8.

In MySQL, I have my Media table with File for emplacement. I thought Symfony created a upload directory, but the link looks like this:

Media

+---------+----+--------------+----------------+
| Libelle | ID | Cat_Media_ID | file           |
+---------+----+--------------+----------------+
| test    |  1 |            1 | /tmp/phpY0oLd6 |
+---------+----+--------------+----------------+

Is it normal? Should I specify the directory where files needs to be added?

EDIT 2:

My Media Entity:

<?php

namespace AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Media
 *
 * @ORM\Table(name="Media", indexes={@ORM\Index(name="fk_Media_Cat_Media1_idx", columns={"Cat_Media_ID"})})
 * @ORM\Entity
 */
class Media
{
    /**
     * @var string
     *
     * @ORM\Column(name="Libelle", type="string", length=45, nullable=true)
     */
    private $libelle;

    /**
     * @var integer
     *
     * @ORM\Column(name="ID", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \AdminBundle\Entity\CatMedia
     *
     * @ORM\ManyToOne(targetEntity="AdminBundle\Entity\CatMedia")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="Cat_Media_ID", referencedColumnName="ID")
     * })
     */
    private $catMedia;


    /**
     * @ORM\Column(type="string")
     *
     *
     * @Assert\File(mimeTypes={ "application/image" })
     */
    private $file;



    /**
     * Set libelle
     *
     * @param string $libelle
     * @return Media
     */
    public function setLibelle($libelle)
    {
        $this->libelle = $libelle;

        return $this;
    }

    /**
     * Get libelle
     *
     * @return string 
     */
    public function getLibelle()
    {
        return $this->libelle;
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set catMedia
     *
     * @param \AdminBundle\Entity\CatMedia $catMedia
     * @return Media
     */
    public function setCatMedia(\AdminBundle\Entity\CatMedia $catMedia = null)
    {
        $this->catMedia = $catMedia;

        return $this;
    }

    /**
     * Get catMedia
     *
     * @return \AdminBundle\Entity\CatMedia 
     */
    public function getCatMedia()
    {
        return $this->catMedia;
    }



    public function setFile($file)
    {
        $this->file = $file;

        return $this;
    }


    public function getFile()
    {
        return $this->file;
    }


}

My Media NewAction Controller:

/**
     * Creates a new Media entity.
     *
     * @Route("/new", name="media_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $media = new Media();
        $form = $this->createForm('AdminBundle\Form\MediaType', $media);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

                // $file stores the uploaded file
                /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
                $file = $media->getFile();

                // Generate a unique name for the file before saving it
                $fileName = md5(uniqid()).'.'.$file->guessExtension();

                // Move the file to the directory where media are stored
                $fileDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/';
                $file->move($fileDir, $fileName);

                // Update the 'media' property to store the file name
                // instead of its contents
                $media->setFile($fileName);



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

            return $this->redirectToRoute('media_show', array('id' => $media->getId()));
        }

        return $this->render('AdminBundle:media:new.html.twig', array(
            'medium' => $media,
            'form' => $form->createView(),
        ));
    }

My media FormType:

<?php

namespace AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;

class MediaType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('libelle')
            ->add('catmedia','entity',  array('class'=>'AdminBundle:CatMedia',
                'property'=>'libelle'))
            ->add('file', FileType::class, array('label' => 'Image (Png or jpg file)'))
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AdminBundle\Entity\Media'
        ));
    }


}

and User Formtype using Media FormType:

<?php

namespace AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UtilisateurType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom')
            ->add('prenom')
            ->add('societe')
            ->add('mail')
            ->add('tel')
            ->add('password')
            ->add('catutilisateur','entity',  array('class'=>'AdminBundle:CatUtilisateur',
                'property'=>'libelle'))
            ->add('media', MediaType::class)



        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AdminBundle\Entity\Utilisateur'
        ));
    }
}

As you can see, i have my move Function. But I do not have the directory uploads into web/, and in the database , I have this famous

+---------+----+--------------+----------------+
| Libelle | ID | Cat_Media_ID | file           |
+---------+----+--------------+----------------+
| test    |  1 |            1 | /tmp/phpY0oLd6 |
+---------+----+--------------+----------------+
7
  • It's just uploaded file by user, you should move that file to some directory after user finish uploading. Commented Feb 2, 2016 at 0:59
  • @malcolm but is not that what I already do in my newAction ? $fileDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/'; $file->move($fileDir, $fileName); Commented Feb 2, 2016 at 6:55
  • 1
    How look Media entity setFile() method? Commented Feb 2, 2016 at 9:42
  • @malcolm i edited my post with setFile() function Commented Feb 3, 2016 at 17:45
  • It's impossible that md5(uniqid()).'.'.$file->guessExtension(); return /tmp/phpY0oLd6 , you paste wrong code or something there that you missing. Is there any functions in your media entity that modify $file property? Commented Feb 3, 2016 at 18:24

1 Answer 1

1

After upload move the file to your desired directory and you will get a File object in return.

$file = $uploadedFile->move($directory, $name);

In Symfony applications, uploaded files are objects of the UploadedFile class, which provides methods for the most common operations when dealing with uploaded files;

See Symfony Api

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

4 Comments

I have perhaps not been specific enough in my post . I edited it with the controller. As you can see, i have a move function. but it is not working. Thx for your help :)
No errors, nothing. only some deprecated warnings. phpStorm say "FILE" namespace is undefined
You are probably doing a flush on $media->setFile($fileName); as malcolm asked can you post it here
done. in don't understood what is wrong with this function !

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.