Symfony2 beta upload file

Yes, there is currently no documentation on how to upload a file in Symfony2. Yes, it took me hours to figure out how to do it. Yes, of course I will share!
I don’t think this is the correct Symfony way to do it, but it works and I believe it is secure. I would like to access the $uploadedFile object from the $form object instead of the $request. If you know how to do it, please write a comment.

The code is pretty straight forward and documented so I figure I just post it.

My controller:

public function indexAction()
{
    //create a simple form with one filed called "dataFile" of type "file"
    $form = $this->get('form.factory')
	 ->createBuilder('form')
	 ->add("dataFile","file", array("required"=>true))
	 ->getForm();

    $request = $this->get('request');
    if ($request->getMethod() == 'POST') {
        //bind the request, (note the enctype in the template)
      	$form->bindRequest($request); 

    	if ($form->isValid()) {
            //if the form is valid, try to get the uploaded file object
            //Symfony\Component\HttpFoundation\File\UploadedFile
    	    $files=$request->files->get($form->getName());
    	    $uploadedFile=$files["dataFile"]["file"]; //"dataFile" is the name on the field
    	
            //once you have the uploadedFile object there is some sweet functions you can run
    	    $uploadedFile->getPath();//returns current (temporary) path
    	    $uploadedFile->getOriginalName();
    	    $uploadedFile->getMimeType();

            //and most important is move(), 
    	    $uploadedFile->move(
    	        $_SERVER['DOCUMENT_ROOT']."/uploads",
    	        $uploadedFile->getOriginalName()
    	    );

    	    $this->get('session')->setFlash('notice', 'The file is uploaded!');
    	}
    	else{
    		//form is not valid
	        	
    	}
    }//end if request method == POST	
	    	
    return $this->render('ApplicationMyBundle:Default:index.html.twig',
        array("form"=>$form->createView()));
    }

My template:

{# note the form_enctype, without it the form will not bind in the controller #}
<form action="" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" class="submit" id="form_submit" value="Save" />
</form>

12 Comments

  • 1
    Rick
    maj 24, 2011 - 15:19 | Permalink

    Thanks for your code, will give it a try!

    in stead of the $uploadedFile you could use:
    $uploadedFile = $form['dataFile']->getData();

  • 2
    Tobias
    juni 9, 2011 - 09:25 | Permalink

    No Rick, you are wrong.

    //This gives the temp filename
    $form['dataFile']->getData();

    //This gives an instance of Symfony\Component\HttpFoundation\File\UploadedFile
    $uploadedFile=$files["dataFile"]["file"];

    It might be hard to validate because UploadedFile returns the temp filename when converted to a string.

  • 3
    Quentin
    juni 16, 2011 - 04:54 | Permalink

    Thanks ! It works fine. I will continue to dig to see how it works will the AdminBundle.
    Cheers

  • 4
    Ellit
    oktober 20, 2011 - 11:35 | Permalink

    Hello,

    You can access the uploaded file from the form like this:

    public function uploadAction()
    {
    // …

    if ($form->isValid()) {
    $someNewFilename = …

    $form['attachment']->getData()->move($dir, $someNewFilename);

    // …
    }

    // …
    }

    taken from:
    http://symfony.com/doc/current/reference/forms/types/file.html

    • 5
      Tobias
      oktober 21, 2011 - 01:13 | Permalink

      Thanks, But at the time I wrote this, (17th of May) there was no documentation at all on this. Im not even sure you could execute that line of code back then,

  • 6
    Ali Elmasry
    november 16, 2011 - 10:09 | Permalink

    Dear,

    I tried implement you code in my project by symfony 2.0 and show this error

    Exception: Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::serialize() must return a string or NULL

    Exception: Serialization of ‘Symfony\Component\HttpFoundation\File\UploadedFile’ is not allowed

  • Kommentera

    E-postadressen publiceras inte. Obligatoriska fält är märkta *

    *


    Följande HTML-taggar och attribut är tillåtna: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>