MeursaultF
MeursaultF

Reputation: 219

Symfony 2.8 upload file error: Unable to create the uploads/ directory

i use Symfony 2.8.

i have an error when i try to upload file from form:

Unable to create the "/var/www/erdf/src/AdminBundle/Entity/../../../../web/uploads/img" directory

I first thought it was a permission problem. So i added permission commands to web/ directory:

sudo chmod -R 775 web/

and:

sudo chown -R meursault:www-data web/

but it still not works. Same error. I see the probleme is a 500 eror and not a 403.

there is 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
 * @ORM\HasLifecycleCallbacks
 */
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;


    /**
     * @var string
     *
     * @ORM\Column(name="url", type="string", length=255)
     */
    private $url;

    /**
     * @var string
     *
     * @ORM\Column(name="alt", type="string", length=255)
     */
    private $alt;

    private $tempFilename;

    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;
    }



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

        return $this;
    }

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


    /**
     * Set alt
     *
     * @param string $alt
     * @return string
     */
    public function setAlt($alt)
    {
        $this->alt = $alt;

        return $this;
    }

    /**
     * Get alt
     *
     * @return Media
     */
    public function getAlt()
    {
        return $this->alt;
    }

    /**
     * Set file
     *
     * @param string $file
     * @return string
     */
    public function setfile($file)
    {
        $this->file = $file;

        return $this;
    }

    /**
     * Get file
     *
     * @return Media
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        // Si jamais il n'y a pas de fichier (champ facultatif)
        if (null === $this->file) {
            return;
        }

        // Le nom du fichier est son id, on doit juste stocker également son extension
        // Pour faire propre, on devrait renommer cet attribut en « extension », plutôt que « url »
        $this->url = $this->file->guessExtension();

        // Et on génère l'attribut alt de la balise <img>, à la valeur du nom du fichier sur le PC de l'internaute
        $this->alt = $this->file->getClientOriginalName();
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        // Si jamais il n'y a pas de fichier (champ facultatif)
        if (null === $this->file) {
            return;
        }

        // Si on avait un ancien fichier, on le supprime
        if (null !== $this->tempFilename) {
            $oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
            if (file_exists($oldFile)) {
                unlink($oldFile);
            }
        }

        // On déplace le fichier envoyé dans le répertoire de notre choix
        $this->file->move(
            $this->getUploadRootDir(), // Le répertoire de destination
            $this->id.'.'.$this->url   // Le nom du fichier à créer, ici « id.extension »
        );
    }

    /**
     * @ORM\PreRemove()
     */
    public function preRemoveUpload()
    {
        // On sauvegarde temporairement le nom du fichier, car il dépend de l'id
        $this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        // En PostRemove, on n'a pas accès à l'id, on utilise notre nom sauvegardé
        if (file_exists($this->tempFilename)) {
            // On supprime le fichier
            unlink($this->tempFilename);
        }
    }

    public function getUploadDir()
    {
        // On retourne le chemin relatif vers l'image pour un navigateur
        return 'uploads/img';
    }

    protected function getUploadRootDir()
    {
        // On retourne le chemin relatif vers l'image pour notre code PHP
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    public function getWebPath()
    {
        return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
    }


}

and my New controller function:

/**
     * 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
                /*
                // 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(),
        ));
    }

I tried to create by myself the uploads/img directory, and add the permissions. But symfony try to create it anyway, and send same error.

Maybe the route is false ? I dont't know...

Thanks in advance for your help :)

EDIT: SOLVED

sorry to have wasted your time.

after tests, the route wasn't correct. i changed:

protected function getUploadRootDir()
    {
        // On retourne le chemin relatif vers l'image pour notre code PHP
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

to

protected function getUploadRootDir()
    {
        // On retourne le chemin relatif vers l'image pour notre code PHP
        return __DIR__.'/../../../web/'.$this->getUploadDir();
    }

Upvotes: 1

Views: 1891

Answers (1)

Beno&#238;t
Beno&#238;t

Reputation: 602

I think you are doing thing wrong to upload your file.

have a look at this bundle : https://github.com/dustin10/VichUploaderBundle

that's the easiest way i know to make fileupload

Upvotes: -1

Related Questions