Laiboa
Laiboa

Reputation: 35

File Upload Symfony

I would like to upload multiple pictures in my form. In fact, is working, but only with the small size of the picture ( like less than 1Mo). When I try to upload a picture with 4/5Mo, I have this error: The file "" does not exist

I noticed that it was due to the size because for small images it works very well.

So, my code : Entity Picture who is related to Activity :

 /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank(message="Please, upload the product brochure as a PNG, GIF, JPEG or JPG file.")
     * @Assert\File(mimeTypes = {"image/png","image/jpeg","image/jpg","image/gif"})
     * @Assert\File(maxSize="50M")
     */
    private $url;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $legende;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Activity", inversedBy="pictures")
     */
    private $activity;

The form pictureType :

->add('url', FileType::class, array('label' => 'Image (JPG, JPEG, PNG, GIF)'))

and the controller, in the create activity ( the picture form is here, when you add an activity, you can choose to add one or many pictures )

 /**
     * @Route("/create_activity", name="create_activity")
     */
    public function create_activity(Request $request, ObjectManager $manager){

        $activity = new Activity();
        $form = $this->createForm(ActivityType::class, $activity);
        $form->handleRequest($request);

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

            $pictures = $activity->getPictures(); // On récupère toutes les photos ajoutées

            if($pictures){ // S'il y a des photos
                foreach ($pictures as $picture ) { // Pour chaque photo
                   $file = $picture->getUrl(); // On récupère l'url uploadé
          // ERROR COMING HERE at $file->guessExtension();
                   $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension(); // On génère un nom de fichier
                   // Move the file to the directory where brochures are stored
                        try {
                            $file->move( // On l'ajoute dans le répertoire
                                $this->getParameter('pictures_directory'),
                                $fileName
                            );
                        } catch (FileException $e) {
                            // ... handle exception if something happens during file upload
                        }
                        $picture->setUrl($fileName);
                }
            }


           $activity->setCreatedAt(new \DateTime());
           $activity->setDeleted(0);
           $manager->persist($activity);
           $manager->flush();

        return $this->redirectToRoute('show_activity', ['id' => $activity->getId()]);
        }

        return $this->render('activity/create_activity.html.twig', [
            'formActivity' => $form->createView(),
            'activity' => $activity
        ]);
    }

I made many 'echo; exit;' for know where the error is coming, and she comes from "$file->guessExtension();"

Thanks a lot for your help!

Upvotes: 1

Views: 217

Answers (1)

Alexandre Blond
Alexandre Blond

Reputation: 76

If your $file is an instance of UploadedFile (which it should be in your case), you can use the method $file->getError() to know if there was a problem during the upload of your file.

This method will return an integer corresponding to this documentation : http://php.net/manual/en/features.file-upload.errors.php

In your case, i bet you will have a UPLOAD_ERR_INI_SIZE error. To solve this, you can see the solution here : Change the maximum upload file size

EDIT

Here's an example for you :

/** @var UploadedFile $file */
$file = $picture->getUrl();

if (UPLOAD_ERR_OK !== $file->getError()) {
    throw new UploadException($file->getErrorMessage());
}

Upvotes: 1

Related Questions