How to Upload Files
Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
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
// src/AppBundle/Form/ProductType.php
namespace AppBundle\Form;
use AppBundle\Entity\Product;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('brochure', FileType::class, array('label' => 'Brochure (PDF file)'))
// ...
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Product::class,
));
}
}
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 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) }}
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// src/AppBundle/Controller/ProductController.php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
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(ProductType::class, $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();
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();
// Move the file to the directory where brochures are stored
try {
$file->move(
$this->getParameter('brochures_directory'),
$fileName
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates 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(),
));
}
/**
* @return string
*/
private function generateUniqueFileName()
{
// md5() reduces the similarity of the file names generated by
// uniqid(), which is based on timestamps
return md5(uniqid());
}
}
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:
- 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; - 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;
- 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:
1
<a href="{{ asset('uploads/brochures/' ~ product.brochure) }}">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 separate service:
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
// src/AppBundle/FileUploader.php
namespace AppBundle;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileUploader
{
private $targetDirectory;
public function __construct($targetDirectory)
{
$this->targetDirectory = $targetDirectory;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
try {
$file->move($this->getTargetDirectory(), $fileName);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
return $fileName;
}
public function getTargetDirectory()
{
return $this->targetDirectory;
}
}
Then, define a service for this class:
1 2 3 4 5 6
# app/config/services.yml
services:
# ...
app.brochure_uploader:
class: AppBundle\FileUploader
arguments: ['%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->isSubmitted() && $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 51 52 53
// src/AppBundle/EventListener/BrochureUploadListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;
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) {
$fileName = $this->uploader->upload($file);
$entity->setBrochure($fileName);
} elseif ($file instanceof File) {
// prevents the full file path being saved on updates
// as the path is set on the postLoad listener
$entity->setBrochure($file->getFilename());
}
}
}
Now, register this class as a Doctrine listener:
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 }
This listener 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 18 19 20 21
// ...
use Symfony\Component\HttpFoundation\File\File;
// ...
class BrochureUploadListener
{
// ...
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Product) {
return;
}
if ($fileName = $entity->getBrochure()) {
$entity->setBrochure(new File($this->uploader->getTargetDir().'/'.$fileName));
}
}
}
After adding these lines, configure the listener to also listen for the
postLoad
event.