多个上传Symfony2

时间:2016-08-08 15:23:09

标签: php symfony upload

我从Symfony开始,我遇到了多次上传。

我只能上传一个文件,并尝试修改此代码以进行多次上传。

这是我的错误:

Expected argument of type "Symfony\Component\HttpFoundation\File\UploadedFile", "array" given

这是我的代码:

ImageArticleType:

$builder
        ->add('file', 'file', array('label' => 'Choisir mes images', 'multiple'=> true))
    ;

我的实体 ImageArticle.php

<?php

namespace AD\PlatformBundle\Entity;

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

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

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

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

    /**
     * @var File
     *  
     * @Assert\File(
     *     maxSize = "1M",
     *     mimeTypes = {
     *          "image/jpeg", 
     *          "image/gif", 
     *          "image/png", 
     *          },
     *     maxSizeMessage = "La taille maximum du fichier doit etre inférieur ou égale à 1MB. Pour reduire sa taille vous pouvez utiliser le site : compressjpeg.com",
     *     mimeTypesMessage = "Seulement les fichiers .jpeg / .gif /.png sont acceptés"
     * )
     */
    private $file;

    private $tempFileName;

    public function getFile()
    {   
        return $this->file;
    }

    public function setFile(UploadedFile $file)
    {

        $this->file = $file;

        if (null !== $this->url)
        {
            $this->tempFileName = $this->url;
            $this->url=null;
            $this->alt=null;
        }
    }
    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set url
     *
     * @param string $url
     *
     * @return ImageArticle
     */
    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 ImageArticle
     */
    public function setAlt($alt)
    {
        $this->alt = $alt;

        return $this;
    }

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

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null === $this->file)
        {
            return;
        }


        //On add un extension pour le fichier.
        $this->url = $this->file->guessExtension();
        //Le alt est le nom du fichier du client.
        $this->alt=  $this->file->getClientOriginalName();

    }

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

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

        //On deplace
        $this->file->move
        (
            $this->getUploadRootDir(),
            $this->id.'.'.$this->url    
        );
    }

    /**
     *@ORM\PreRemove()
     */
    public function preRemoveUpload()
    {
        $this->tempFileName = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
    }

    /**
     * 
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if(file_exists($this->tempFileName))
        {
            unlink($this->tempFileName);
        }
    }
    public function getUploadDir()
    {
        return 'upload/img/';
    }

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

    public function __toString()
    {
        return $this->getUploadDir().$this->id.'.'.$this->getUrl();
    }

    /**
     * Set source
     *
     * @param string $source
     *
     * @return Image
     */
}

我在想一个简单的foreach循环,但它不起作用......

3 个答案:

答案 0 :(得分:1)

使用multiple选项上传文件可能有点棘手。使用multiple = false选项,实体类中的$file属性将返回单个UploadedFile实例,multiple = true在调用$entity->getFile()时返回UploadedFile实例数组。这就是为什么你必须手动,在表单提交,动作中实现上传过程,没有生命周期回调。像这样:

动作:

....
$image = new ImageArticle();

$form = $this->createForm('YOUR_FORM', $image);
$form->handleRequest($request);

if ($form->isValid()) {
    ...

    foreach ($image->getFile() as $uploadedFile) {
        $image = new ImageArticle();
        $image
            // setters go here
        ;

        // Upload process go here

        $image->setFile(null);
    }

    $this->get('doctrine.orm.entity_manager')->flush();

    ....
}

以下是我项目的截图: enter image description here

答案 1 :(得分:0)

那样的东西?

public function newArticleAction(Request $request)
{
   $article = new Article();
   $article->setUser($this->getUser());

   $imageArticle = new ImageArticle();

   $form = $this->get('form.factory')->create(new \AD\PlatformBundle\Form\ArticleType(), $article, $image); 
    if($form->handleRequest($request)->isValid())
    {
        foreach($imageArticle->getFile() as $imageArticle)
        {
            $imageArticle = new ImageArticle();

            $imageArticle->setAlt($imageArticle->getAlt());
            $imageArticle->setUrl($imageArticle->getUrl());
            $imageArticle->setFile($imageArticle->getFile());

            $imageArticle->preRemoveUpload();
            $imageArticle->preUpload();
            $imageArticle->upload();

        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($article);
        $em->flush();

        $request->getSession()->getFlashBag()->add('notice', 'Article publié ! :)');
        return $this->redirect($this->generateUrl('va_platform_blog'));
    }
    return $this->render('ADPlatformBundle:Cars:newarticle.html.twig', array(
        'form' =>$form->createView(),
    ));
}

答案 2 :(得分:0)

您的图片是保存在文章实体还是其他内容中(当我得到您的答案时,我会进行更改)?

我对您的代码做了一些小改动。我不确定所有的代码,但我认为这应该有效

public function newArticleAction(Request $request)
{
   $article = new Article();
   $images = new ImageArticle();

   $form = $this->get('form.factory')->create(ArticleType::class, $article, $images);
   $form->handleRequest($request);

   if($form->isValid())
   {
       $article->setUser($this->getUser());
       // other article fields, if needed

       foreach($images->getFile() as $image)
       {
           $images->setAlt($image->getAlt());
           $images->setUrl($image->getUrl());
           $images->setFile($image->getFile());

           $images->preRemoveUpload();
           $images->preUpload();
           $images->upload();
       }

       $em = $this->getDoctrine()->getManager();
       $em->persist($article);
       $em->flush();

       $request->getSession()->getFlashBag()->add('notice', 'Article publié ! :)');

       return $this->redirect($this->generateUrl('va_platform_blog'));
    }

    return $this->render('ADPlatformBundle:Cars:newarticle.html.twig', [
        'form' => $form->createView(),
    ]);
}