9951 explained code solutions for 126 technologies

php-symfonyHow to upload a file in PHP Symfony?

Uploading a file in PHP Symfony is a simple process.

  1. Create a form with a file input field:
$form = $this->createFormBuilder()
    ->add('file', FileType::class)
  1. Handle the form submission:

if ($form->isSubmitted() && $form->isValid()) {
    // ...
  1. Get the file from the request:
$file = $form->get('file')->getData();
  1. Move the file to the desired location:
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

try {
} catch (FileException $e) {
    // ...
  1. Save the file name to the database:

For more information, please refer to the Symfony documentation.

Edit this code on GitHub