【问题标题】:Symfony 2.8 upload file error: Unable to create the uploads/ directorySymfony 2.8 上传文件错误:无法创建上传/目录
【发布时间】:2016-05-21 22:50:06
【问题描述】:

我使用 Symfony 2.8。

当我尝试从表单上传文件时出错:

无法创建 “/var/www/erdf/src/AdminBundle/Entity/../../../../web/uploads/img” 目录

我一开始以为是权限问题。所以我在 web/ 目录中添加了权限命令:

sudo chmod -R 775 web/

和:

sudo chown -R meursault:www-data web/

但它仍然无法正常工作。同样的错误。我看到问题是 500 错误而不是 403。

有我的媒体实体:

<?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();
    }


}

还有我的新控制器功能:

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

我尝试自己创建 uploads/img 目录,并添加权限。但是 symfony 无论如何都会尝试创建它,并发送相同的错误。

也许路线是假的?不知道……

提前感谢您的帮助:)

编辑:已解决

很抱歉浪费了您的时间。

经过测试,路线不正确。我改变了:

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

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

【问题讨论】:

    标签: php symfony upload


    【解决方案1】:

    我认为您上传文件时做错了。

    看看这个捆绑包:https://github.com/dustin10/VichUploaderBundle

    这是我知道的最简单的文件上传方法

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 2016-04-18
      • 2011-04-27
      • 2012-09-23
      • 2021-08-31
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多