Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多上传Symfony2_Php_Symfony_Upload - Fatal编程技术网

Php 多上传Symfony2

Php 多上传Symfony2,php,symfony,upload,Php,Symfony,Upload,我是从Symfony开始的,我被多重上传所困扰 我可以上传一个文件,我尝试修改这个代码进行多次上传 这是我的错误: Expected argument of type "Symfony\Component\HttpFoundation\File\UploadedFile", "array" given 这是我的密码: ImageArticleType: $builder ->add('file', 'file', array('label' => 'Choisir

我是从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
     */
}

使用
多个
选项上载文件可能有点棘手。使用
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();

    ....
}
以下是我的项目截图: 像这样的事

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

您的图像是保存在文章实体中还是其他实体中(我会在得到您的答案后进行更改)

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

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

您的错误告诉您试图传递一个
数组
,而不是类
上载文件
的项。尝试从您的字段中删除
多个
选项,这可能会生成一个数组。谢谢您的回复!如果删除“多个”选项,则无法选择多个文件。是的,我知道,但如果仍然只有一个文件出现错误,请尝试。如果你的代码不正确,我认为你应该尝试在你的控制器中做一个
foreach
循环,单独保存每个文件。哦,好的。是的,只有一个文件,工作正常。在我的控制器中,我保存/刷新我的文章。我试图在我的文章中包含多个图片,因此在ArticleType中,我像这样调用ImageArticleType
->add('imagearticle',newimagearticletype(),array('required'=>true))
。我不能在ImageArticle实体中创建foreach吗?不,在您的控制器中,请查看下面的答案。我得到了以下错误
类型错误:传递给Symfony\Component\Form\FormFactory::create()的参数3必须是数组类型,给定的对象,在第296行的/var/www/html/QrCar/src/AD/PlatformBundle/Controller/carscocontroller.php中调用此错误告诉您,
$This->get('form.factory')->create()的
$image
参数在对象中而不是数组中。您的图像是保存在
文章
实体中还是其他实体中?@Wako
createForm()
方法接收
('String formTypeName',Object dataObject,Array options)
,我想您正在将对象作为第三个参数传递。我有两个实体:Article.php和ImageArticle.phpSame error<代码>类型错误:传递给Symfony\Component\Form\FormFactory::create()的参数3必须是在提交或页面加载过程中给定的类型数组、对象
?在页面加载过程中,是否可以转储
$Form->isValid()中的
$images
?如果这不起作用,请评论foreach