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)
    ->getForm();
  1. Handle the form submission:
$form->handleRequest($request);

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 {
    $file->move(
        $this->getParameter('files_directory'),
        $fileName
    );
} catch (FileException $e) {
    // ...
}
  1. Save the file name to the database:
$entity->setFileName($fileName);
$entityManager->persist($entity);
$entityManager->flush();

For more information, please refer to the Symfony documentation.

Edit this code on GitHub