symfony2 how to upload file without doctrine?

Rahul picture Rahul · Jun 10, 2013 · Viewed 25.8k times · Source

Is it possible to upload files in symfony2 WITHOUT using doctrine? With doctrine, its example is given here: http://symfony.com/doc/2.2/cookbook/doctrine/file_uploads.html

Is there a simple way to upload files, like in core PHP we have move_uploaded_file() function with which we can move the uploaded to file after the form is submitted.

For now when I submit the form in symfony this is what I get in 'files' section of request array (Symfony\Component\HttpFoundation\Request)

 [files] => Symfony\Component\HttpFoundation\FileBag Object
        (
            [parameters:protected] => Array
                (
                    [upload_cover] => Symfony\Component\HttpFoundation\File\UploadedFile Object
                        (
                            [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 
                            [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => secret_of_success.png
                            [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/png
                            [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 157958
                            [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
                            [pathName:SplFileInfo:private] => C:\xampp\tmp\php3636.tmp
                            [fileName:SplFileInfo:private] => php3636.tmp
                        )

                )

        )

Answer

devsheeep picture devsheeep · Jun 10, 2013

After submitting the form, move the file to your desired directory and you will get a File object in return.

foreach($request->files as $uploadedFile) {
    $name = //...
    $file = $uploadedFile->move($directory, $name);
}

Take a look at the API-Manual for the full featured documentation of this class.