2016-05-04 4 views
0

В AppBundle \ Etity \ Image У меня есть:symfony3 изображение не загружено

<?php 

namespace AppBundle\Entity; 

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

/** 
* @ORM\Entity 
* @ORM\Table(name="images") 
* @ORM\HasLifecycleCallbacks 
*/ 
class Image 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    private $id; 
    /** 
    * @ORM\Column(type="string", length=255) 
    * @Assert\NotBlank 
    */ 
    private $name; 
    /** 
    * @ORM\Column(type="string", length=255, nullable=true) 
    * @Assert\NotBlank 
    */ 
    private $path; 
    /** 
    * @Assert\Image(maxSize="10M", mimeTypes="image/jpeg", minWidth = 600, minHeight = 400) 
    * @Assert\NotBlank 
    */ 
    private $file; 
    /** 
    * @ORM\Column(type="string", length=255) 
    * @Assert\NotBlank 
    */ 
    private $alt; 

    private $temp; 

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

    /** 
    * @return mixed 
    */ 
    public function getName() 
    { 
     return $this->name; 
    } 

    /** 
    * @param mixed $name 
    */ 
    public function setName($name) 
    { 
     $this->name = $name; 
    } 

    /** 
    * @return mixed 
    */ 
    public function getPath() 
    { 
     return $this->path; 
    } 

    /** 
    * @param mixed $path 
    */ 
    public function setPath($path) 
    { 
     $this->path = $path; 
    } 

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

    /** 
    * @param mixed $alt 
    */ 
    public function setAlt($alt) 
    { 
     $this->alt = $alt; 
    } 

    public function getAbsolutePath() 
    { 
     return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->path; 
    } 

    public function getUploadRootDir() 
    { 
     return __DIR__ . '/../../../../web/' . $this->getUploadDir(); 
    } 

    public function getUploadDir() 
    { 
     return 'images/full'; 
    } 

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

     // check if we have an old image path 
     if (isset($this->path)) { 
      // store the old name to delete after the update 
      $this->temp = $this->path; 
      $this->path = null; 
     } else { 
      $this->path = 'initial'; 
     } 
    } 

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


    } 

    /** 
    * @ORM\PrePersist() 
    * @ORM\PreUpdate() 
    */ 
    public function preUpload() 
    { 
     if (null !== $this->getFile()) { 
      // do whatever you want to generate a unique name 
      $filename = sha1(uniqid(mt_rand(), true)); 
      $this->path = $filename.'.'.$this->getFile()->guessExtension(); 
     } 
    } 

    /** 
    * @ORM\PostPersist() 
    * @ORM\PostUpdate() 
    */ 
    public function upload() 
    { 
     if (null === $this->getFile()) { 
      return; 
     } 

     // if there is an error when moving the file, an exception will 
     // be automatically thrown by move(). This will properly prevent 
     // the entity from being persisted to the database on error 
     $this->getFile()->move($this->getUploadRootDir(), $this->path); 

     // check if we have an old image 
     if (isset($this->temp)) { 
      // delete the old image 
      unlink($this->getUploadRootDir().'/'.$this->temp); 
      // clear the temp image path 
      $this->temp = null; 
     } 

     $this->file = null; 
    } 

    /** 
    * @ORM\PostRemove() 
    */ 
    public function removeUpload() 
    { 
     $file = $this->getAbsolutePath(); 

     if ($file) { 
      unlink($file); 
     } 
    } 
} 

, который используется в AppBundle \ Entity \ Post.php как это:

/** 
* @ORM\ManyToOne(targetEntity="Image", cascade="all") 
* @ORM\JoinColumn(name="image_id", referencedColumnName="id") 
*/ 
private $teaserImage; 

В AppBundle \ Form \ Тип \ PostType.php у меня есть это:

<?php 

namespace AppBundle\Form\Type; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolver; 
use AppBundle\Entity\Post; 

/** 
* Defines the form used to create and manipulate blog posts. 
*/ 
class PostType extends AbstractType 
{ 
    /** 
    * {@inheritdoc} 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('title', null, array('label' => 'Title')) 
      ->add('summary', null, array('label' => 'Summary')) 
      ->add('teaserImage', 'AppBundle\Form\Type\ImageType', array('label' => 'Image')) 
      ->add('content', null, array(
       'attr' => array('rows' => 20), 
       'label' => 'Content', 
      )) 
     ; 
    } 

    /** 
    * {@inheritdoc} 
    */ 
    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'AppBundle\Entity\Post', 
     )); 
    } 
} 

по некоторым причинам изображения не загружены в указанный каталог (или где-либо еще), и я не уверен, белый Я ошибся. Я был бы благодарен за любые идеи. Спасибо.

ответ

0

Проблема связана с

return __DIR__ . '/../../../../web/' . $this->getUploadDir(); 

В этом случае я изменил предыдущую строку:

return __DIR__ . '/../../../web/' . $this->getUploadDir(); 

Это происходит потому, что моя сущность находится в SRC/AppBundle/Entity и пойти корневой директории ему нужно переместить 3 каталога назад. Также это плохая идея для жестких кодов в сущности. Я соответствующим образом изменил свой пример.

+0

Другое дело, что вы всегда должны проверить, существует ли каталог, который вы хотите записать. –