Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload file using a form without an entity class

Tags:

php

symfony

I've tried to upload file using a form without an entity class. No luck so far.

  // Controller
  public function uploadAction() {
    $request = $this->getRequest();
    $form = $this->createFormBuilder()
            ->add('images', 'file') // If I remove this line data is submitted correctly
            ->add('dir', 'text')
            ->getForm();

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

      $data = $form->getData();
      var_dump($data);
    }   
    else
      return $this->render('OverseerMainBundle:Default:form.html.twig', array(
          'form' => $form->createView(),
      )); 
  }

// form.html.twig
{% block body %}
<form action="{{ path('OverseerMainBundle_upload') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}

    <input type="submit" />
</form>
{% endblock %}

So far var_dump echoes:

array(2) { ["images"]=> NULL ["dir"]=> NULL }

However if I remove line ->add('images', 'file') everything is ok:

array(1) { ["dir"]=> string(4) "test" }

P.S. I've checked html code of form and attribute enctype="multipart/form-data" is presented. So it's not an issue.

like image 509
Molecular Man Avatar asked Feb 03 '12 14:02

Molecular Man


2 Answers

Also I hope this would help others:

if ($form->isValid()) {
        $file = $form->get('file')->getData();
        $name = $file->getClientOriginalName();
        $dir = __DIR__.'/../../../../web/uploads';

        $file->move($dir, $name) ;
    }
like image 130
Safwan Bakais Avatar answered Sep 20 '22 02:09

Safwan Bakais


Have you checked that the file doesn't exceed the server maximum file size limit? The default is 2MB. I haven't used Symfony 2.0 yet so I am not sure of that.

like image 28
thenetimp Avatar answered Sep 19 '22 02:09

thenetimp