DEMOS / Upload

Keep Files on Errors

One form, two file fields: a FileType and an UploadType. Save it with an empty title. The first field comes back empty. The second keeps its file, and the next submit sends a few hundred bytes instead of the whole document.

ux.symfony.com
Up to 1 MiB - PDF

A file input cannot be filled back

Both fields sit in the same form. Browsers never pre-fill <input type="file">: when the title fails validation, the FileType field comes back empty.

The visitor picks the file again, and the next submit sends the whole file a second time.

31$builder
32    // The file travels with the form.
33    ->add('classic', FileType::class, [
34        'label' => 'Document',
35        'required' => false,
36        'constraints' => [
37            new File(
38                maxSize: '1M',
39                mimeTypes: 'application/pdf',
40            ),
41        ],
42    ])
43    // The file travels first, the form carries a reference.
44    ->add('upload', UploadType::class, [
45        'label' => 'Document',
46        'uploader' => 'documents',
47        'required' => false,
48    ])
49    ->add('title', TextType::class, [
50        'constraints' => [
51            new NotBlank(message: 'Please enter a title.'),
52        ],
53    ])
54;

Upload first, submit a reference

UploadType sends the file as soon as it is selected. The form then holds a signed reference in a hidden input. A failed validation renders that reference again, like any other value.

The token carries the upload id, uploader, field, temporary path, name, MIME type, size, checksum, and expiry, signed with Symfony's UriSigner. meta only feeds the display. Tampered or expired tokens are rejected.

<input type="file">
{# empty after upload: the file is already on the server #}

<input type="hidden" name="keep_files_form[upload]" value='{
    "token": "_expiration=1790281692&_hash=FolvRLV4…&f=world-domination-plan.pdf&i=e54f3ad8…&m=application/pdf&s=819218&u=documents&…",
    "meta": {"filename": "world-domination-plan.pdf", "mimeType": "application/pdf", "size": 819218}
}'>

The controller does not change

Both fields go through the same handleRequest() and isValid(). For each one, getData() returns an UploadedFile: read its name and size, then move() it or read its stream into your own storage.

26$form = $this->createForm(KeepFilesForm::class);
27$form->handleRequest($request);
28if ($form->isSubmitted() && $form->isValid()) {
29    // A real application moves the files to their final place here. This public server
30    // destroyed the upload already, PHP removes the classic one itself: it only reads both names.
31    $this->addFlash('keep_files_success', [
32        'classic' => $form->get('classic')->getData()?->getClientOriginalName(),
33        'upload' => $form->get('upload')->getData()?->getClientOriginalName(),
34    ]);
35
36    return $this->redirectToRoute('app_demo_upload_keep_files');
37}
Author smnandre
Published 2026-11-15