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')) {
        $form->handleRequest($request);

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

            $fileUpload->handleForm(
                uploadedFile: $form->get('image')->getData(), // Symfony\Component\HttpFoundation\File\UploadedFile or null
                path: $fileDirectory,
                // optional
                afterUploadCallback: function ($filename) use ($entity, $fileDirectory) {
                    $entity->setImage($fileDirectory.$filename);
                },
                // 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());
});