How to Upload Files

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 brochureFilename in the Product entity:

  1. // src/Entity/Product.php
  2. namespace App\Entity;
  3. use Doctrine\ORM\Mapping as ORM;
  4. class Product
  5. {
  6. // ...
  7. /**
  8. * @ORM\Column(type="string")
  9. */
  10. private $brochureFilename;
  11. public function getBrochureFilename()
  12. {
  13. return $this->brochureFilename;
  14. }
  15. public function setBrochureFilename($brochureFilename)
  16. {
  17. $this->brochureFilename = $brochureFilename;
  18. return $this;
  19. }
  20. }

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

The next step is to add a new field to the form that manages the Product entity. This must be a FileType field so the browsers can display the file upload widget. The trick to make it work is to add the form field as “unmapped”, so Symfony doesn’t try to get/set its value from the related entity:

  1. // src/Form/ProductType.php
  2. namespace App\Form;
  3. use App\Entity\Product;
  4. use Symfony\Component\Form\AbstractType;
  5. use Symfony\Component\Form\Extension\Core\Type\FileType;
  6. use Symfony\Component\Form\FormBuilderInterface;
  7. use Symfony\Component\OptionsResolver\OptionsResolver;
  8. use Symfony\Component\Validator\Constraints\File;
  9. class ProductType extends AbstractType
  10. {
  11. public function buildForm(FormBuilderInterface $builder, array $options)
  12. {
  13. $builder
  14. // ...
  15. ->add('brochure', FileType::class, [
  16. 'label' => 'Brochure (PDF file)',
  17. // unmapped means that this field is not associated to any entity property
  18. 'mapped' => false,
  19. // make it optional so you don't have to re-upload the PDF file
  20. // every time you edit the Product details
  21. 'required' => false,
  22. // unmapped fields can't define their validation using annotations
  23. // in the associated entity, so you can use the PHP constraint classes
  24. 'constraints' => [
  25. new File([
  26. 'maxSize' => '1024k',
  27. 'mimeTypes' => [
  28. 'application/pdf',
  29. 'application/x-pdf',
  30. ],
  31. 'mimeTypesMessage' => 'Please upload a valid PDF document',
  32. ])
  33. ],
  34. ])
  35. // ...
  36. ;
  37. }
  38. public function configureOptions(OptionsResolver $resolver)
  39. {
  40. $resolver->setDefaults([
  41. 'data_class' => Product::class,
  42. ]);
  43. }
  44. }

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):

  1. {# templates/product/new.html.twig #}
  2. <h1>Adding a new product</h1>
  3. {{ form_start(form) }}
  4. {# ... #}
  5. {{ form_row(form.brochure) }}
  6. {{ form_end(form) }}

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

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use App\Form\ProductType;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  7. use Symfony\Component\HttpFoundation\File\UploadedFile;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. class ProductController extends AbstractController
  11. {
  12. /**
  13. * @Route("/product/new", name="app_product_new")
  14. */
  15. public function new(Request $request)
  16. {
  17. $product = new Product();
  18. $form = $this->createForm(ProductType::class, $product);
  19. $form->handleRequest($request);
  20. if ($form->isSubmitted() && $form->isValid()) {
  21. /** @var UploadedFile $brochureFile */
  22. $brochureFile = $form->get('brochure')->getData();
  23. // this condition is needed because the 'brochure' field is not required
  24. // so the PDF file must be processed only when a file is uploaded
  25. if ($brochureFile) {
  26. $originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
  27. // this is needed to safely include the file name as part of the URL
  28. $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
  29. $newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
  30. // Move the file to the directory where brochures are stored
  31. try {
  32. $brochureFile->move(
  33. $this->getParameter('brochures_directory'),
  34. $newFilename
  35. );
  36. } catch (FileException $e) {
  37. // ... handle exception if something happens during file upload
  38. }
  39. // updates the 'brochureFilename' property to store the PDF file name
  40. // instead of its contents
  41. $product->setBrochureFilename($newFilename);
  42. }
  43. // ... persist the $product variable or any other work
  44. return $this->redirectToRoute('app_product_list');
  45. }
  46. return $this->render('product/new.html.twig', [
  47. 'form' => $form->createView(),
  48. ]);
  49. }
  50. }

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

  1. # config/services.yaml
  2. # ...
  3. parameters:
  4. brochures_directory: '%kernel.project_dir%/public/uploads/brochures'

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

  1. In Symfony applications, uploaded files are objects of the Symfony\Component\HttpFoundation\File\UploadedFile class. This class provides methods for the most common operations when dealing with uploaded files;
  2. 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()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/File/UploadedFile.php "Symfony\Component\HttpFoundation\File\UploadedFile::getExtension()")), the original file size ([getClientSize()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/File/UploadedFile.php "Symfony\Component\HttpFoundation\File\UploadedFile::getClientSize()")) and the original file name ([getClientOriginalName()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/File/UploadedFile.php "Symfony\Component\HttpFoundation\File\UploadedFile::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()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/File/UploadedFile.php "Symfony\Component\HttpFoundation\File\UploadedFile::guessExtension()") method to let Symfony guess the right extension according to the file MIME type;

Deprecated since version 4.1: The [getClientSize()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/File/UploadedFile.php "Symfony\Component\HttpFoundation\File\UploadedFile::getClientSize()") method was deprecated in Symfony 4.1 and will be removed in Symfony 5.0. Use getSize() instead.

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

  1. <a href="{{ asset('uploads/brochures/' ~ product.brochureFilename) }}">View brochure (PDF)</a>

Tip

When creating a form to edit an already persisted item, the file form type still expects a Symfony\Component\HttpFoundation\File\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. use Symfony\Component\HttpFoundation\File\File;
  2. // ...
  3. $product->setBrochureFilename(
  4. new File($this->getParameter('brochures_directory').'/'.$product->getBrochureFilename())
  5. );

Creating an Uploader Service

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

  1. // src/Service/FileUploader.php
  2. namespace App\Service;
  3. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  4. use Symfony\Component\HttpFoundation\File\UploadedFile;
  5. class FileUploader
  6. {
  7. private $targetDirectory;
  8. public function __construct($targetDirectory)
  9. {
  10. $this->targetDirectory = $targetDirectory;
  11. }
  12. public function upload(UploadedFile $file)
  13. {
  14. $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  15. $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
  16. $fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
  17. try {
  18. $file->move($this->getTargetDirectory(), $fileName);
  19. } catch (FileException $e) {
  20. // ... handle exception if something happens during file upload
  21. }
  22. return $fileName;
  23. }
  24. public function getTargetDirectory()
  25. {
  26. return $this->targetDirectory;
  27. }
  28. }

Tip

In addition to the generic Symfony\Component\HttpFoundation\File\Exception\FileException class there are other exception classes to handle failed file uploads: Symfony\Component\HttpFoundation\File\Exception\CannotWriteFileException, Symfony\Component\HttpFoundation\File\Exception\ExtensionFileException, Symfony\Component\HttpFoundation\File\Exception\FormSizeFileException, Symfony\Component\HttpFoundation\File\Exception\IniSizeFileException, Symfony\Component\HttpFoundation\File\Exception\NoFileException, Symfony\Component\HttpFoundation\File\Exception\NoTmpDirFileException, and Symfony\Component\HttpFoundation\File\Exception\PartialFileException.

Then, define a service for this class:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Service\FileUploader:
    5. arguments:
    6. $targetDirectory: '%brochures_directory%'
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <!-- ... -->
    8. <service id="App\Service\FileUploader">
    9. <argument>%brochures_directory%</argument>
    10. </service>
    11. </container>
  • PHP

    1. // config/services.php
    2. use App\Service\FileUploader;
    3. $container->autowire(FileUploader::class)
    4. ->setArgument('$targetDirectory', '%brochures_directory%');

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

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. use App\Service\FileUploader;
  4. use Symfony\Component\HttpFoundation\Request;
  5. // ...
  6. public function new(Request $request, FileUploader $fileUploader)
  7. {
  8. // ...
  9. if ($form->isSubmitted() && $form->isValid()) {
  10. /** @var UploadedFile $brochureFile */
  11. $brochureFile = $form->get('brochure')->getData();
  12. if ($brochureFile) {
  13. $brochureFileName = $fileUploader->upload($brochureFile);
  14. $product->setBrochureFilename($brochureFileName);
  15. }
  16. // ...
  17. }
  18. // ...
  19. }

Using a Doctrine Listener

The previous versions of this article explained how to handle file uploads using Doctrine listeners. However, this is no longer recommended, because Doctrine events shouldn’t be used for your domain logic.

Moreover, Doctrine listeners are often dependent on internal Doctrine behavior which may change in future versions. Also, they can introduce performance issues unwillingly (because your listener persists entities which cause other entities to be changed and persisted).

As an alternative, you can use Symfony events, listeners and subscribers.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.