Skip to content

File upload handler

App\Core\Form\FileUploadHandler is a service and helps you to upload a file. See example below.

use App\Core\Form\FileUploadHandler;
use App\Entity\Foo;
use App\Form\FooType;
use Symfony\Component\HttpFoundation\Request;

public function upload(Request $request, FileUploadHandler $fileUpload)
    $entity = new Foo();
    $form = $this->createForm(FooType::class, $foo);

    if ($request->isMethod('POST')) {

        if ($form->isValid()) {
            $fileDirectory = 'uploads/';
            $keepOriginalFilename = false;

                uploadedFile: $form->get('image')->getData(), // Symfony\Component\HttpFoundation\File\UploadedFile or null
                path: $fileDirectory,
                // optional
                afterUploadCallback: function ($filename) use ($entity, $fileDirectory) {
                // optional
                keepOriginalFilename: $keepOriginalFilename

            // ...

If you need to generate custom filenames, FileUploadHandler allows you to define a generator:

use Symfony\Component\HttpFoundation\File\UploadedFile;

$fileUpload->setFilenameGenerator(function(UploadedFile $file) {
    return sprintf('%d.%s', mt_rand(), $file->guessExtension());