symfony2多个文件上传

时间:2015-04-10 10:23:23

标签: symfony entity multifile-uploader

  

我想向每个实体插入多个图像   因为这段代码效果很好,但它只需要添加最后一张图片。   有没有办法使用简单的表格上传Symfony2的所有图像?

equipe实体    

namespace Examen\CoupedumondeBundle\Entity;

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

/**
 * equipe
 *
 * @ORM\Table()
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class equipe
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

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

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

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

    /**
     * @Assert\File(maxSize="6000000")
     */
    public $file;


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

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


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

    /**
     * Set pays
     *
     * @param string $pays
     * @return equipe
     */
    public function setPays($pays)
    {
        $this->pays = $pays;

        return $this;
    }

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

    /**
     * Set capitaine
     *
     * @param string $capitaine
     * @return equipe
     */
    public function setCapitaine($capitaine)
    {
        $this->capitaine = $capitaine;

        return $this;
    }

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

    /**
     * Set continent
     *
     * @param string $continent
     * @return equipe
     */
    public function setContinent($continent)
    {
        $this->continent = $continent;

        return $this;
    }

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

    /**
     * Set coach
     *
     * @param string $coach
     * @return equipe
     */
    public function setCoach($coach)
    {
        $this->coach = $coach;

        return $this;
    }

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


    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    public $path;

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

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

    protected function getUploadRootDir()
    {
        // le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
        // le document/image dans la vue.
        return 'uploads/documents';
    }
    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->file) {
            // faites ce que vous voulez pour générer un nom unique
            $this->path = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
        }
    }

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

        // s'il y a une erreur lors du déplacement du fichier, une exception
        // va automatiquement être lancée par la méthode move(). Cela va empêcher
        // proprement l'entité d'être persistée dans la base de données si
        // erreur il y a
        $this->file->move($this->getUploadRootDir(), $this->path);

        unset($this->file);
    }

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

}

equipeType

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('pays')
        ->add('capitaine')
        ->add('continent')
        ->add('coach')
        ->add('file','file',array(
            "attr" => array(
                "accept" => "image/*",
                "multiple" => "multiple",
            )
        ));
}

控制器

public function insertionAction()
{
    $em= $this->getDoctrine()->getManager();
    $pers = new equipe;
    $form= $this->createForm(new equipeType, $pers);
    $request= $this->container->get('request');


    if($request->getMethod()=='POST')
    {
        $form->bind($request);
        if ($form->isValid()){
            $em->persist($pers);
            $em->flush();
            return new RedirectResponse($this->get('router')->generate('examen_coupedumonde_homepage'));
        }

    }

    return $this->render('ExamenCoupedumondeBundle:Default:insertion.html.twig',array('form'=>$form->createView()));
}

有人帮我,谢谢你:)。

2 个答案:

答案 0 :(得分:0)

我认为你必须嵌入一组表格(图片):见http://symfony.com/doc/current/cookbook/form/form_collections.html。这是一种方式......

答案 1 :(得分:0)

好吧,您可以使用PHP和Doctrine轻松添加多个文件。

if(isset($_FILES['files']))
    {
        $errors= array();
        foreach($_FILES['files']['tmp_name'] as $key => $tmp_name )
        {
            $file_name = $_FILES['files']['name'][$key];
            $file_size =$_FILES['files']['size'][$key];
            $file_tmp =$_FILES['files']['tmp_name'][$key];
            $file_type=$_FILES['files']['type'][$key];
            if($file_size > 6097152) //whatever size you want
            {
                $errors[]='File size must be less than 6 MB';
            }
            $entity = new Entity; //your file entity

            //Do whatever you want with the entity...

            $request = $this->get('request');
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush(); 
            $desired_dir=__DIR__.'/../../../../web/[Your desired folder]/'.$entity->getId()."/";
            if(empty($errors)==true)
            {
                if(is_dir($desired_dir)==false)
                {
                    mkdir("$desired_dir", 0700);        // Create directory if it does not exist
                }
                if(is_dir("$desired_dir/".$file_name)==false)
                {
                    move_uploaded_file($file_tmp,__DIR__.'/../../../../web/[Your desired folder]/'.$entity->getId()."/".$file_name);
                }
                else
                {                                  //rename the file if another one exist
                    $new_dir=__DIR__.'/../../../../web/Flightpics/'.$flight->getId()."/".$file_name.time();
                    rename($file_tmp,$new_dir) ;
                }
            }
            else
            {
                //print errors if needed
            }
        }
        if(empty($error)){
                //print success if needed
        }
    }

所有文件都将被处理到您的网站/ [您的文件夹] / [您的实体ID]文件夹中。