Проблемы с загрузкой нескольких файлов в Symfony2

Я делаю приложение Symfony2, которое должно иметь возможность загрузки нескольких изображений. Я сделал загрузку одного файла, используя запись в поваренной книге:Как обрабатывать загрузку файлов с помощью Doctrine , которая отлично работает. Я реализовал обратные вызовы жизненного цикла для загрузки и удаления.

Теперь мне нужно превратить это в систему многократной загрузки. Я также прочитал несколько ответов от Stack Overflow, но, похоже, ничего не работает.

Вопрос о переполнении стека:

  1. Загрузка нескольких файлов с помощью Symfony2
  2. Загрузка нескольких файлов в Symfony 2

На данный момент у меня есть следующий код:

Файл Сущность:

id;
    }

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

    /**
     * Get path
     *
     * @return string 
     */
    public function getPath()
    {
        return $this->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()
    {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
        return 'uploads';
    }

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

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->file) {
            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->file->move($this->getUploadRootDir(), $this->path);

        unset($this->file);
    }

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

FileController:

createFormBuilder($file)
            ->add('file','file',array(
                    "attr" => array(
                        "accept" => "image/*",
                        "multiple" => "multiple",
                    )
                ))
            ->getForm()
        ;

        if ($this->getRequest()->getMethod() === 'POST') {
            $form->bindRequest($this->getRequest());
                $em = $this->getDoctrine()->getEntityManager();

                $em->persist($file);
                $em->flush();

                $this->redirect($this->generateUrl('file_upload'));
        }

        return array('form' => $form->createView());
    }
}

и upload.html.twig:

{% extends '::base.html.twig' %}

{% block body %}

Upload File

{{ form_widget(form.file) }}
{% endblock %}

Я не знаю, что сделать, чтобы эта система работала как система загрузки нескольких файлов. Я сохранил комментарии, поскольку они из руководств, которым я следовал, чтобы я мог помнить, что делает что.

ОБНОВЛЕНИЕ:

Новый код формы:

$images_form = $this->createFormBuilder($file)
    ->add('file', 'file', array(
            "attr" => array(
                "multiple" => "multiple",
                "name" => "files[]",
            )
        ))
    ->getForm()
;

Новый код ветки формы:

{{ form_label(images_form.file) }} {{ form_errors(images_form.file) }} {{ form_widget(images_form.file, { 'attr': {'name': 'files[]'} }) }} {{ form_rest(images_form) }}

14
задан Community 23 May 2017 в 11:46
поделиться