Skip to main content

File Upload via form

Setting up a Route

To use the input type=file element in a form, you must first define a custom Controller & Method that can receive the data sent from that form. To do this you must use a POST Route. To do this, just add a methods={"POST"} to your Route declaration like this:

@Route("/route/path", name="frontend.route.path", methods={"POST"})

You'll also need to inject 2 things into your Controller: a Media Repository and the FileSaver Class.

Now, if you send your form data to your route, your file should be in the global $_FILES php variable.

Saving the file: Media Object

Now we need to save the file as a new MediaFile object. For this we need a few specifics:

$mediaFile = new MediaFile($path, $type, $extension, $size);

path you can get with $file['tmp_name'].

type you can get with $file['type'].

extension is a bit more difficult. You'll need to convert type or name to just the file extension. Write a convert method that makes sense for this.

size you can get with $file['size'].

That's the MediaFile done!

Inserting the File into the Database

This is easier. Before we can save the file, we need to reserve a spot for it in the Database. To do this, simply use:

$mediaRepository->upsert([[ 'id' => $id, 'name' => $name ]], $c);

$c is a Context, not SalesChannelContext.

!> Pay attention to the double array!

Persisting the file

Now we only need to persist the File. To do this, we use the aptly named persistFileToMedia method of our fileSaver.

$filesaver->persistFileToMedia($mediaFile, $name, $id, $c );

$name needs to be a unique name! To easily do this, add part of the $id to the filename.

Done!