Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Cookbook
  4. Controller
  5. How to Upload Files
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • Creating an Uploader Service
  • Using a Doctrine Listener

How to Upload Files

Edit this page

Warning: You are browsing the documentation for Symfony 2.3, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Upload Files

Note

Instead of handling file uploading yourself, you may consider using the VichUploaderBundle community bundle. This bundle provides all the common operations (such as file renaming, saving and deleting) and it's tightly integrated with Doctrine ORM, MongoDB ODM, PHPCR ODM and Propel.

Imagine that you have a Product entity in your application and you want to add a PDF brochure for each product. To do so, add a new property called brochure in the Product entity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Entity/Product.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

class Product
{
    // ...

    /**
     * @ORM\Column(type="string")
     *
     * @Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
     * @Assert\File(mimeTypes={ "application/pdf" })
     */
    private $brochure;

    public function getBrochure()
    {
        return $this->brochure;
    }

    public function setBrochure($brochure)
    {
        $this->brochure = $brochure;

        return $this;
    }
}

Note that the type of the brochure column is string instead of binary or blob because it just stores the PDF file name instead of the file contents.

Then, add a new brochure field to the form that manages the Product entity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Form/ProductType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('brochure', 'file', array('label' => 'Brochure (PDF file)'))
            // ...
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Product',
        ));
    }

    public function getName()
    {
        return 'product';
    }
}

Now, update the template that renders the form to display the new brochure field (the exact template code to add depends on the method used by your application to customize form rendering):

  • Twig
  • PHP
1
2
3
4
5
6
7
8
{# app/Resources/views/product/new.html.twig #}
<h1>Adding a new product</h1>

{{ form_start(form) }}
    {# ... #}

    {{ form_row(form.brochure) }}
{{ form_end(form) }}
1
2
3
4
5
6
<!-- app/Resources/views/product/new.html.twig -->
<h1>Adding a new product</h1>

<?php echo $view['form']->start($form) ?>
    <?php echo $view['form']->row($form['brochure']) ?>
<?php echo $view['form']->end($form) ?>

Finally, you need to update the code of the controller that handles the form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// src/AppBundle/Controller/ProductController.php
namespace AppBundle\ProductController;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Product;
use AppBundle\Form\ProductType;

class ProductController extends Controller
{
    /**
     * @Route("/product/new", name="app_product_new")
     */
    public function newAction(Request $request)
    {
        $product = new Product();
        $form = $this->createForm(new ProductType(), $product);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // $file stores the uploaded PDF file
            /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
            $file = $product->getBrochure();

            // Generate a unique name for the file before saving it
            $fileName = md5(uniqid()).'.'.$file->guessExtension();

            // Move the file to the directory where brochures are stored
            $file->move(
                $this->container->getParameter('brochures_directory'),
                $fileName
            );

            // Update the 'brochure' property to store the PDF file name
            // instead of its contents
            $product->setBrochure($fileName);

            // ... persist the $product variable or any other work

            return $this->redirect($this->generateUrl('app_product_list'));
        }

        return $this->render('product/new.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}

Now, create the brochures_directory parameter that was used in the controller to specify the directory in which the brochures should be stored:

1
2
3
4
5
# app/config/config.yml

# ...
parameters:
    brochures_directory: '%kernel.root_dir%/../web/uploads/brochures'

There are some important things to consider in the code of the above controller:

  1. When the form is uploaded, the brochure property contains the whole PDF file contents. Since this property stores just the file name, you must set its new value before persisting the changes of the entity;
  2. In Symfony applications, uploaded files are objects of the UploadedFile class. This class provides methods for the most common operations when dealing with uploaded files;
  3. A well-known security best practice is to never trust the input provided by users. This also applies to the files uploaded by your visitors. The UploadedFile class provides methods to get the original file extension (getExtension()), the original file size (getClientSize()) and the original file name (getClientOriginalName()). However, they are considered not safe because a malicious user could tamper that information. That's why it's always better to generate a unique name and use the guessExtension() method to let Symfony guess the right extension according to the file MIME type;

You can use the following code to link to the PDF brochure of a product:

  • Twig
  • PHP
1
<a href="{{ asset('uploads/brochures/' ~ product.brochure) }}">View brochure (PDF)</a>
1
2
3
<a href="<?php echo $view['assets']->getUrl('uploads/brochures/'.$product->getBrochure()) ?>">
    View brochure (PDF)
</a>

Tip

When creating a form to edit an already persisted item, the file form type still expects a File instance. As the persisted entity now contains only the relative file path, you first have to concatenate the configured upload path with the stored filename and create a new File class:

1
2
3
4
5
6
use Symfony\Component\HttpFoundation\File\File;
// ...

$product->setBrochure(
    new File($this->getParameter('brochures_directory').'/'.$product->getBrochure())
);

Creating an Uploader Service

To avoid logic in controllers, making them big, you can extract the upload logic to a seperate service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/FileUploader.php
namespace AppBundle;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileUploader
{
    private $targetDir;

    public function __construct($targetDir)
    {
        $this->targetDir = $targetDir;
    }

    public function upload(UploadedFile $file)
    {
        $fileName = md5(uniqid()).'.'.$file->guessExtension();

        $file->move($this->targetDir, $fileName);

        return $fileName;
    }
}

Then, define a service for this class:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
# app/config/services.yml
services:
    # ...
    app.brochure_uploader:
        class: AppBundle\FileUploader
        arguments: ['%brochures_directory%']
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
    http://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <!-- ... -->

    <service id="app.brochure_uploader" class="AppBundle\FileUploader">
        <argument>%brochures_directory%</argument>
    </service>
</container>
1
2
3
4
5
6
7
8
// app/config/services.php
use Symfony\Component\DependencyInjection\Definition;

// ...
$container->setDefinition('app.brochure_uploader', new Definition(
    'AppBundle\FileUploader',
    array('%brochures_directory%')
));

Now you're ready to use this service in the controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Controller/ProductController.php

// ...
public function newAction(Request $request)
{
    // ...

    if ($form->isValid()) {
        $file = $product->getBrochure();
        $fileName = $this->get('app.brochure_uploader')->upload($file);

        $product->setBrochure($fileName);

        // ...
    }

    // ...
}

Using a Doctrine Listener

If you are using Doctrine to store the Product entity, you can create a Doctrine listener to automatically upload the file when persisting the entity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// src/AppBundle/EventListener/BrochureUploadListener.php
namespace AppBundle\EventListener;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use AppBundle\Entity\Product;
use AppBundle\FileUploader;

class BrochureUploadListener
{
    private $uploader;

    public function __construct(FileUploader $uploader)
    {
        $this->uploader = $uploader;
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    private function uploadFile($entity)
    {
        // upload only works for Product entities
        if (!$entity instanceof Product) {
            return;
        }

        $file = $entity->getBrochure();

        // only upload new files
        if (!$file instanceof UploadedFile) {
            return;
        }

        $fileName = $this->uploader->upload($file);
        $entity->setBrochure($fileName);
    }
}

Now, register this class as a Doctrine listener:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
# app/config/services.yml
services:
    # ...
    app.doctrine_brochure_listener:
        class: AppBundle\EventListener\BrochureUploadListener
        arguments: ['@app.brochure_uploader']
        tags:
            - { name: doctrine.event_listener, event: prePersist }
            - { name: doctrine.event_listener, event: preUpdate }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
    http://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <!-- ... -->

    <service id="app.doctrine_brochure_listener"
        class="AppBundle\EventListener\BrochureUploaderListener"
    >
        <argument type="service" id="app.brochure_uploader"/>

        <tag name="doctrine.event_listener" event="prePersist"/>
        <tag name="doctrine.event_listener" event="preUpdate"/>
    </service>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// app/config/services.php
use Symfony\Component\DependencyInjection\Reference;

// ...
$definition = new Definition(
    'AppBundle\EventListener\BrochureUploaderListener',
    array(new Reference('brochures_directory'))
);
$definition->addTag('doctrine.event_listener', array(
    'event' => 'prePersist',
));
$definition->addTag('doctrine.event_listener', array(
    'event' => 'preUpdate',
));
$container->setDefinition('app.doctrine_brochure_listener', $definition);

This listeners is now automatically executed when persisting a new Product entity. This way, you can remove everything related to uploading from the controller.

Tip

This listener can also create the File instance based on the path when fetching entities from the database:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ...
use Symfony\Component\HttpFoundation\File\File;

// ...
class BrochureUploadListener
{
    // ...

    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        $fileName = $entity->getBrochure();

        $entity->setBrochure(new File($this->targetPath.'/'.$fileName));
    }
}

After adding these lines, configure the listener to also listen for the postLoad event.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
The life jacket for your team and your project

The life jacket for your team and your project

Check Code Performance in Dev, Test, Staging & Production

Check Code Performance in Dev, Test, Staging & Production

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Marc Laporte, a Symfony contributor

Thanks Marc Laporte for being a Symfony contributor

4 commits • 8 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia