For uploading images with Symfony 4 / Flex I use Doctrine EventListeners, as soon as the Entity gets persisted the image will be uploaded. I’ll demonstrate in this article how to do it.
For you ease of use, I included all code snippets in a gist. view gists
The setup
Setting up the Image Entity
Every image will have it’s own entry inside the database, this way you can always re-use the image or even change it’s source file without re-linking the it to the custom entity.
The Image class contains the following attributes: file, alt, id
where alt is optional. The file attribute is where the actual filename will be stored.
Create a File Uploader
The image uploader receives the upload directory as defined in the services.yml file. Defining it in the services.yml like this:
App\Service\FileUploader:
arguments:
$targetDirectory: '%image_directory%'
This will automate the uploading process, receiving the uploaded file, moving it to the directory and returning the filename.
You can steal the code from here: File upload gist