ux-upload
Symfony UX Upload: replace FileType with UploadType for image previews, drag and drop, dropzones, clipboard paste, client-side file validation, progress bars, background file uploads, chunking, pause and resume, and uploads that survive form validation errors.
Install
npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/ux-upload
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
git clone https://github.com/smnandre/symfony-ux-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
UX Upload
Upload files in the background before a Symfony Form is submitted. Users select, drop or paste files, follow progress, pause and resume, and fix other fields' validation errors while their files stay uploaded. UploadType replaces FileType and returns an UploadedFile that extends HttpFoundation's, so move() keeps working.
Since Symfony UX 3.8+. The package is experimental: its API may still change.
Installation
composer require symfony/ux-upload
Until a Flex recipe exists, register the bundle and the routes yourself:
// config/bundles.php
Symfony\UX\Upload\UXUploadBundle::class => ['all' => true],
# config/routes/ux_upload.yaml
ux_upload:
resource: '@UXUploadBundle/config/routes.php'
prefix: /_ux/upload
trailing_slash_on_root: false
Requires StimulusBundle. Assets: php bin/console importmap:install (AssetMapper) or npm install && npm run dev (Encore, Reprise). The stylesheet is opt-in (see Styling). Schedule cleanup from day one:
*/15 * * * * cd /path/to/app && php bin/console ux:upload:cleanup --age=24h
Every upload needs an identity. With SecurityBundle the logged-in user is used; an anonymous visitor needs more than a firewall to be identified. For public forms, add a session-based resolver (see Security below).
If several application nodes handle uploads, read the distributed deployment configuration for shared storage and locking.
Quick Start
# config/packages/ux_upload.yaml
ux_upload:
uploaders:
documents:
max_size: 50M
allowed_types: [application/pdf]
use Symfony\UX\Upload\Form\UploadType;
$builder
->add('document', UploadType::class, [
'uploader' => 'documents',
'constraints' => [new NotBlank()],
])
->add('title', TextType::class, ['constraints' => [new NotBlank()]]);
use Symfony\UX\Upload\Upload\UploadedFile;
if ($form->isSubmitted() && $form->isValid()) {
/** @var UploadedFile|null $upload */
$upload = $form->get('document')->getData();
if (null !== $upload) {
$upload->move($directory, $upload->getId().'.'.($upload->guessExtension() ?? 'bin'));
}
return $this->redirectToRoute('document_new');
}
Render with form_row(form.document) as usual. Name the final file from getId(): repeated submissions hit the same target, and client filenames stay out of the way.
Field Options
| Option | Default | Notes |
|---|---|---|
uploader |
default |
Named server policy |
max_size |
null |
Inherits the uploader; may only narrow it |
allowed_types |
[] |
MIME list; may only narrow the uploader |
multiple |
false |
Returns list<UploadedFile> |
max_files |
null |
Count limit with multiple |
layout |
compact |
compact or dropzone |
show_preview |
false |
Image previews |
auto_upload |
true |
Start right after selection |
compression |
false |
gzip bodies and chunks (also needs the uploader) |
widget_attr |
[] |
Attributes on the widget container (attr goes to the native input) |
help_text, invalid_message |
generated |
Required and mapped by default, like FileType; pass required: false for an optional file.
For dropzones, previews and client-side presentation, see customizing the upload field. To react to progress, completion or validation errors in Stimulus, see the browser events reference.
Named Uploaders
ux_upload:
max_size: 100M # global limit, 0 disables it
uploaders:
avatars:
max_size: 5M
allowed_types: [image/jpeg, image/png, image/webp]
chunk_size: 1M
completed_ttl: 3600
documents:
max_size: 100M
allowed_types: [application/pdf]
The uploader name is signed into the policy and the token: a token from another uploader is rejected. Overridable per uploader: max_size, allowed_types, chunk_size, parallel_chunks, compression, integrity_algorithm, completed_ttl, max_pending_per_owner.
Saving Files
UploadedFile is a temporary reference. Copy it into your own storage, then record the final location:
$stream = $upload->openStream(); // no local copy, works with Flysystem
try {
$attachment = $this->storage->storeOnce($upload->getId(), $stream, $upload->getClientOriginalName());
} finally {
fclose($stream);
}
- Make saving idempotent on
getId()(double click, proxy retry). Under concurrency, enforce it with a unique constraint rather than a lookup before the write. - Never call
delete()in the same request: a second valid submission may still need the stream. Letux:upload:cleanupremove it aftercompleted_ttl. - Never persist
getStoragePath(); cleanup deletes that path. - Metadata getters (
getClientOriginalName(),getMimeType(),getSize(),getChecksum()...) never touch the file: they read signed data.getPathname(),getContent(), theFile/Imageconstraints and the dev profiler copy the whole file locally first.
Security
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\UX\Upload\Security\UploadContext;
use Symfony\UX\Upload\Security\UploadContextResolverInterface;
final class SessionUploadContextResolver implements UploadContextResolverInterface
{
public function __construct(private readonly RequestStack $requestStack) {}
public function resolve(): UploadContext
{
$request = $this->requestStack->getMainRequest();
if (null === $request || !$request->hasSession()) {
return new UploadContext();
}
$session = $request->getSession();
$owner = $session->get('upload_owner');
if (!\is_string($owner) || '' === $owner) {
$owner = bin2hex(random_bytes(16));
$session->set('upload_owner', $owner);
}
return new UploadContext(ownerId: $owner);
}
}
# config/services.yaml
services:
Symfony\UX\Upload\Security\UploadContextResolverInterface:
alias: App\Upload\SessionUploadContextResolver
Tokens are bound to owner, tenant, form field and uploader, and signed with kernel.secret. allow_anonymous: true shares one context (and one quota) between all visitors: only with a rate_limiter. CSRF is checked automatically when symfony/security-csrf is installed.
Live Components
use Symfony\UX\Upload\LiveComponent\Attribute\UploadTarget;
use Symfony\UX\Upload\LiveComponent\ComponentWithUploadTrait;
#[AsLiveComponent]
final class ProfilePhoto
{
use ComponentWithUploadTrait;
use DefaultActionTrait;
#[LiveProp]
#[UploadTarget(uploader: 'avatars')]
public ?string $photo = null; // nullable string: holds the signed token
public function getPhotoUpload(): ?UploadedFile
{
return $this->getUpload('photo');
}
}
<div{{ attributes.defaults(stimulus_controller('symfony/ux-upload/live-upload', {property: 'photo'})) }}>
{{ form_row(this.uploadForm.photo) }} {# an UploadType built with 'data' => this.photoUpload #}
</div>
The bridge calls the applyUpload action on upload completion; clearUpload deletes the temporary file and nulls the property. Keep the field out of data-live-ignore.
Styling
Opt in to the stylesheet in assets/controllers.json ("@symfony/ux-upload/dist/style.min.css": true under the upload controller's autoimport), then theme with --ux-upload-accent, --ux-upload-bg, --ux-upload-border, --ux-upload-radius... Without it, the native file input stays visible and usable, and your form theme rules. To change markup, {% use '@UXUpload/form_theme.html.twig' %} in your own form theme and override blocks (ux_upload_actions, ux_upload_item...) keeping the data-ux-upload-* hooks.
Key Principles
Configure policy on named uploaders; fields only narrow it.
Identify every visitor. Logged-in user, a session resolver, or a deliberate allow_anonymous with rate limiting.
Temporary is temporary. Copy with openStream() or move(), persist idempotently, let cleanup delete.
Fit chunk_size to PHP and proxy limits. Files up to chunk_size go in one multipart POST; larger files go in chunks.
References
- Symfony UX package page (Markdown summary) ·
symfony/ux-uploadon Packagist. - For field customization, validation, retries and deployment, see the Symfony UX Upload documentation or its RST source.
- Reference (configuration,
UploadedFileAPI, server and DOM events, JavaScriptUploader, form theme blocks, storage backends, testing): references/reference.md - Gotchas (installation, limits, tokens, production, debugging): references/gotchas.md
Demos
Each demo shows the code behind the example. Upload demo catalog
- Keep Files on Errors
- Upload with Turbo
- Live Avatar
- Simple & Enhanced Input
- Dropzone & Card Grid
- Resumable Large Files
The package page also embeds a PDF form that keeps its file after validation errors and a photo grid with image previews.
See Also
- live-component:
ComponentWithUploadTraitupdates a component as soon as the upload completes. - ux-image: serve the saved images through an image CDN.
Files (symfony-ux-skills)
-
references
-
gotchas.md 4.6 KB
Loading… -
reference.md 9.1 KB
Loading…
-
-
SKILL.md 10.3 KB
--- name: ux-upload description: 'Symfony UX Upload: replace FileType with UploadType for image previews, drag and drop, dropzones, clipboard paste, client-side file validation, progress bars, background file uploads, chunking, pause and resume, and uploads that survive form validation errors.' license: MIT metadata: author: Simon André url: https://smnandre.dev --- # UX Upload Upload files in the background before a Symfony Form is submitted. Users select, drop or paste files, follow progress, pause and resume, and fix other fields' validation errors while their files stay uploaded. `UploadType` replaces `FileType` and returns an `UploadedFile` that extends HttpFoundation's, so `move()` keeps working. Since Symfony UX 3.8+. The package is **experimental**: its API may still change. ## Installation ```bash composer require symfony/ux-upload ``` Until a Flex recipe exists, register the bundle and the routes yourself: ```php // config/bundles.php Symfony\UX\Upload\UXUploadBundle::class => ['all' => true], ``` ```yaml # config/routes/ux_upload.yaml ux_upload: resource: '@UXUploadBundle/config/routes.php' prefix: /_ux/upload trailing_slash_on_root: false ``` Requires StimulusBundle. Assets: `php bin/console importmap:install` (AssetMapper) or `npm install && npm run dev` (Encore, Reprise). The stylesheet is opt-in (see Styling). Schedule cleanup from day one: ```text */15 * * * * cd /path/to/app && php bin/console ux:upload:cleanup --age=24h ``` **Every upload needs an identity.** With SecurityBundle the logged-in user is used; an anonymous visitor needs more than a firewall to be identified. For public forms, add a session-based resolver (see Security below). If several application nodes handle uploads, read the [distributed deployment configuration](references/reference.md#distributed) for shared storage and locking. ## Quick Start ```yaml # config/packages/ux_upload.yaml ux_upload: uploaders: documents: max_size: 50M allowed_types: [application/pdf] ``` ```php use Symfony\UX\Upload\Form\UploadType; $builder ->add('document', UploadType::class, [ 'uploader' => 'documents', 'constraints' => [new NotBlank()], ]) ->add('title', TextType::class, ['constraints' => [new NotBlank()]]); ``` ```php use Symfony\UX\Upload\Upload\UploadedFile; if ($form->isSubmitted() && $form->isValid()) { /** @var UploadedFile|null $upload */ $upload = $form->get('document')->getData(); if (null !== $upload) { $upload->move($directory, $upload->getId().'.'.($upload->guessExtension() ?? 'bin')); } return $this->redirectToRoute('document_new'); } ``` Render with `form_row(form.document)` as usual. Name the final file from `getId()`: repeated submissions hit the same target, and client filenames stay out of the way. ## Field Options | Option | Default | Notes | |--------|---------|-------| | `uploader` | `default` | Named server policy | | `max_size` | `null` | Inherits the uploader; may only narrow it | | `allowed_types` | `[]` | MIME list; may only narrow the uploader | | `multiple` | `false` | Returns `list<UploadedFile>` | | `max_files` | `null` | Count limit with `multiple` | | `layout` | `compact` | `compact` or `dropzone` | | `show_preview` | `false` | Image previews | | `auto_upload` | `true` | Start right after selection | | `compression` | `false` | gzip bodies and chunks (also needs the uploader) | | `widget_attr` | `[]` | Attributes on the widget container (`attr` goes to the native input) | | `help_text`, `invalid_message` | generated | | Required and mapped by default, like `FileType`; pass `required: false` for an optional file. For dropzones, previews and client-side presentation, see [customizing the upload field](https://symfony.com/bundles/ux-upload/current/customization.html). To react to progress, completion or validation errors in Stimulus, see the [browser events reference](references/reference.md#browser). ## Named Uploaders ```yaml ux_upload: max_size: 100M # global limit, 0 disables it uploaders: avatars: max_size: 5M allowed_types: [image/jpeg, image/png, image/webp] chunk_size: 1M completed_ttl: 3600 documents: max_size: 100M allowed_types: [application/pdf] ``` The uploader name is signed into the policy and the token: a token from another uploader is rejected. Overridable per uploader: `max_size`, `allowed_types`, `chunk_size`, `parallel_chunks`, `compression`, `integrity_algorithm`, `completed_ttl`, `max_pending_per_owner`. ## Saving Files `UploadedFile` is a **temporary** reference. Copy it into your own storage, then record the final location: ```php $stream = $upload->openStream(); // no local copy, works with Flysystem try { $attachment = $this->storage->storeOnce($upload->getId(), $stream, $upload->getClientOriginalName()); } finally { fclose($stream); } ``` - Make saving idempotent on `getId()` (double click, proxy retry). Under concurrency, enforce it with a unique constraint rather than a lookup before the write. - Never call `delete()` in the same request: a second valid submission may still need the stream. Let `ux:upload:cleanup` remove it after `completed_ttl`. - Never persist `getStoragePath()`; cleanup deletes that path. - Metadata getters (`getClientOriginalName()`, `getMimeType()`, `getSize()`, `getChecksum()`...) never touch the file: they read signed data. `getPathname()`, `getContent()`, the `File`/`Image` constraints and the dev profiler copy the whole file locally first. ## Security ```php use Symfony\Component\HttpFoundation\RequestStack; use Symfony\UX\Upload\Security\UploadContext; use Symfony\UX\Upload\Security\UploadContextResolverInterface; final class SessionUploadContextResolver implements UploadContextResolverInterface { public function __construct(private readonly RequestStack $requestStack) {} public function resolve(): UploadContext { $request = $this->requestStack->getMainRequest(); if (null === $request || !$request->hasSession()) { return new UploadContext(); } $session = $request->getSession(); $owner = $session->get('upload_owner'); if (!\is_string($owner) || '' === $owner) { $owner = bin2hex(random_bytes(16)); $session->set('upload_owner', $owner); } return new UploadContext(ownerId: $owner); } } ``` ```yaml # config/services.yaml services: Symfony\UX\Upload\Security\UploadContextResolverInterface: alias: App\Upload\SessionUploadContextResolver ``` Tokens are bound to owner, tenant, form field and uploader, and signed with `kernel.secret`. `allow_anonymous: true` shares one context (and one quota) between all visitors: only with a `rate_limiter`. CSRF is checked automatically when `symfony/security-csrf` is installed. ## Live Components ```php use Symfony\UX\Upload\LiveComponent\Attribute\UploadTarget; use Symfony\UX\Upload\LiveComponent\ComponentWithUploadTrait; #[AsLiveComponent] final class ProfilePhoto { use ComponentWithUploadTrait; use DefaultActionTrait; #[LiveProp] #[UploadTarget(uploader: 'avatars')] public ?string $photo = null; // nullable string: holds the signed token public function getPhotoUpload(): ?UploadedFile { return $this->getUpload('photo'); } } ``` ```twig <div{{ attributes.defaults(stimulus_controller('symfony/ux-upload/live-upload', {property: 'photo'})) }}> {{ form_row(this.uploadForm.photo) }} {# an UploadType built with 'data' => this.photoUpload #} </div> ``` The bridge calls the `applyUpload` action on upload completion; `clearUpload` deletes the temporary file and nulls the property. Keep the field out of `data-live-ignore`. ## Styling Opt in to the stylesheet in `assets/controllers.json` (`"@symfony/ux-upload/dist/style.min.css": true` under the `upload` controller's `autoimport`), then theme with `--ux-upload-accent`, `--ux-upload-bg`, `--ux-upload-border`, `--ux-upload-radius`... Without it, the native file input stays visible and usable, and your form theme rules. To change markup, `{% use '@UXUpload/form_theme.html.twig' %}` in your own form theme and override blocks (`ux_upload_actions`, `ux_upload_item`...) keeping the `data-ux-upload-*` hooks. ## Key Principles **Configure policy on named uploaders; fields only narrow it.** **Identify every visitor.** Logged-in user, a session resolver, or a deliberate `allow_anonymous` with rate limiting. **Temporary is temporary.** Copy with `openStream()` or `move()`, persist idempotently, let cleanup delete. **Fit `chunk_size` to PHP and proxy limits.** Files up to `chunk_size` go in one multipart POST; larger files go in chunks. ## References - [Symfony UX package page](https://ux.symfony.com/upload) ([Markdown summary](https://ux.symfony.com/upload.md)) · [`symfony/ux-upload` on Packagist](https://packagist.org/packages/symfony/ux-upload). - For field customization, validation, retries and deployment, see the [Symfony UX Upload documentation](https://symfony.com/bundles/ux-upload) or its [RST source](https://raw.githubusercontent.com/symfony/ux/3.x/src/Upload/doc/index.rst). - **Reference** (configuration, `UploadedFile` API, server and DOM events, JavaScript `Uploader`, form theme blocks, storage backends, testing): [references/reference.md](references/reference.md) - **Gotchas** (installation, limits, tokens, production, debugging): [references/gotchas.md](references/gotchas.md) ### Demos Each demo shows the code behind the example. [Upload demo catalog](https://ux.symfony.com/demos/upload) - [Keep Files on Errors](https://ux.symfony.com/demos/upload/keep-files) - [Upload with Turbo](https://ux.symfony.com/demos/upload/turbo) - [Live Avatar](https://ux.symfony.com/demos/upload/live-avatar) - [Simple & Enhanced Input](https://ux.symfony.com/demos/upload/input) - [Dropzone & Card Grid](https://ux.symfony.com/demos/upload/dropzone) - [Resumable Large Files](https://ux.symfony.com/demos/upload/resumable) The package page also embeds a [PDF form that keeps its file after validation errors](https://ux.symfony.com/upload#try) and a [photo grid with image previews](https://ux.symfony.com/upload#field). ## See Also - **live-component**: `ComponentWithUploadTrait` updates a component as soon as the upload completes. - **ux-image**: serve the saved images through an image CDN.
Reviews (0)
No reviews yet.
Comments
Sign in to join the conversation.
No comments yet. Start the conversation.