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
Thanks for your code, will give it a try!
in stead of the $uploadedFile you could use:
$uploadedFile = $form['dataFile']->getData();
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.
Thanks ! It works fine. I will continue to dig to see how it works will the AdminBundle.
Cheers
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
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,
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
The instructions is for Symfony2 beta. Check the documentation for Symfony2: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
You may also ask questions in the forum:
http://symfony2forum.org