Multiple file upload with Symfony2

2019-01-08 10:54发布

I'm trying to upload multiple files via a form, but I can only upload one file at a time, the last one I mark in the browser. Is there a way to upload more images with Symfony2 using a simple form? Here is the twig template of the form I'm using to be able to mark more than one file:

{{ form_widget(form.post_image, { 'attr': {'multiple': 'multiple' }}) }} 

11条回答
爷的心禁止访问
2楼-- · 2019-01-08 11:30

Symfony introduced 'multiple' option to file field type in symfony 2.5

$builder->add('file', 'file', array('multiple' => TRUE));
查看更多
不美不萌又怎样
3楼-- · 2019-01-08 11:34

You need to alter the input file name attribute which need to map an array.

<input type="file" name="name[]" multiple />
查看更多
放我归山
4楼-- · 2019-01-08 11:38

Ok binding issue solved (enctype syntax error) : i'll give you the code i use. maybe it will help...

I have a Gallery Entity

class Gallery
{
    protected $id;
    protected $name;
    protected $description;
    private $urlName;
    public $files; // the array which will contain the array of Uploadedfiles

    // GETTERS & SETTERS ...

    public function getFiles() {
        return $this->files;
    }
    public function setFiles(array $files) {
        $this->files = $files;
    }

    public function __construct() {
        $files = array();
    }
}

I have a form class that generate the form

class Create extends AbstractType {

    public function buildForm(FormBuilder $builder, array $options) {

        $builder->add('name','text',array(
            "label" => "Name",
            "required" => TRUE,
        ));
        $builder->add('description','textarea',array(
            "label" => "Description",
            "required" => FALSE,
        ));
        $builder->add('files','file',array(
            "label" => "Fichiers",
            "required" => FALSE,
            "attr" => array(
                "accept" => "image/*",
                "multiple" => "multiple",
            )
        ));
    }
}

Now in the controller

class GalleryController extends Controller
{
    public function createAction() {
        $gallery = new Gallery();
        $form = $this->createForm(new Create(), $gallery);
        // Altering the input field name attribute
        $formView = $form->createView();
        $formView->getChild('files')->set('full_name', 'create[files][]');

        $request = $this->getRequest();
        if($request->getMethod() == "POST")
        {
            $form->bindRequest($request);

            // print "<pre>".print_r($gallery->getFiles(),1)."</pre>";
            if($form->isValid())
            {
                // Do what you want with your files
                $this->get('gallery_manager')->save($gallery);
                return $this->redirect($this->generateUrl("_gallery_overview"));
            }
        }

        return $this->render("GalleryBundle:Admin:create.html.twig", array("form" => $formView));
    }
}

Hope this help...

NB: If someone know a better way to alter this f** name attribute, maybe in the FormView class or by declaring a new field type, feel free to show us your method...

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-08 11:39

All the suggestions I've found here are workarounds for the real situation.

In order to be able to have multiple attachments, you should use form collection.

Quote from the documentation:

In this entry, you'll learn how to create a form that embeds a collection of many other forms. This could be useful, for example, if you had a Task class and you wanted to edit/create/remove many Tag objects related to that Task, right inside the same form.

http://symfony.com/doc/2.0/cookbook/form/form_collections.html

Example case: You have a document, which form is specified by DocumentType. The document must have multiple attachments, which you can have by defining AttachmentType form and adding it as a collection to the DocumentType form.

查看更多
Melony?
6楼-- · 2019-01-08 11:42

What would happen if there would be some validation errors? Will Symfony Form repost multiple file upload field. Because I tried it and I think for this purpose you need to use collection of file fields. Than symfony form must render all fields have added before correctly.

查看更多
甜甜的少女心
7楼-- · 2019-01-08 11:50

No extra classes needed (except the gallery_manger service but the issue you describe happens before...)

I don't really know what's wrong. Check for your template (maybe wrong enctype... or name attr missmatching)

first try to do a single file upload, check the documentation:

  1. file Field Type
  2. How to handle File Uploads with Doctrine

Once it works, you have to edit some lines.

  1. add input file multiple attribute.
  2. append [] at the end of the input file name attribute (mine is create...[] because my form class name is create, if your is createType it will be createType...[])
  3. init $files as an array.

Copy/paste your code here.

查看更多
登录 后发表回答