File uploads

FileType field

Forms accept files through a file field. The field renders an upload input and hands the file to the form on submit.

Add the field to the builder like any other field. Checks for size and type belong on the same field.

use Symfony\Component\Form\Extension\Core\Type\FileType; class UploadForm { public function fileField($builder): void { $builder->add("attachment", FileType::class); } }

Move the file

Uploaded files start in a temp folder and vanish after the request. Move each file into your storage folder during the same request.

The move call below keeps the safe name you built. After the move the temp copy is gone.

$uploaded = $form->get("attachment")->getData(); if ($uploaded !== null) { $uploaded->move($targetDir, $safeName); }

Safe filenames

Never trust the name from the browser. Lowercase it, strip odd chars, and prefix a unique id so two uploads never clash.

The sketch below turns any name into a safe slug with digits and dashes. Store this name in the database row.

$base = strtolower(trim($original)); $base = preg_replace("/[^a-z0-9]+/", "-", $base); $safeName = uniqid() . "-" . trim($base, "-");

Serve back

To send a file back, return a file response that streams from disk. The browser gets the right headers and the download starts.

The helper below wraps a path in a file response. Add access checks before it when files are private.

use Symfony\Component\HttpFoundation\BinaryFileResponse; function download(string $filePath): BinaryFileResponse { return new BinaryFileResponse($filePath); }

Next: API Platform in one lesson

Article author: Arthur Isaev

Banner image