# File Upload Component
Drag-and-drop file uploads for Rails forms: dropzones, upload buttons, image grids, avatar pickers and chat attachments. One dependency-free Stimulus controller enhances a real `<input type="file">`, so files submit with a normal form, Active Storage direct uploads show progress per file, and existing attachments can be kept or removed. Free component.
## Features
- Drop, browse or paste files; preview images; remove files one by one. The input's `FileList` always matches what is listed, in list order
- Validation by type (`accept`, matched like browsers do, plus extension fallbacks), size (`max_size`) and count (`max_files`), with inline errors and a shake
- Active Storage direct uploads: `queued`, `uploading`, `success` and `error` states, per-file progress, Retry, and uploaded files that stay uploaded when the form is resubmitted
- Optional upload-on-pick (`auto_upload: true`), three files at a time; submitting waits for running uploads
- Existing attachments rendered as items with their `signed_id`, so saving the form keeps them and removing one detaches it
- Server-side validation errors shown under the field (`error:`), with `aria-invalid`
- `required` support without the browser bubble pointing at a hidden input
- Accessible: real input and label, announcements in an `aria-live` region, focus management on removal, `aria-disabled` pickers when full, labelled remove and retry buttons
- Translatable messages, locale-aware file sizes, middle-truncated long names, reduced-motion aware, safe with Turbo cache
- Events for custom uploaders and integrations, and console warnings for setup mistakes
## Implementation Options
| Option | Best for | Files |
|--------|----------|-------|
| ViewComponent | Ruby API: four variants from one call, existing attachments, server errors | `app/components/file_upload/` |
| Shared partial | Apps without ViewComponent: the same options as locals and the same markup | `app/views/shared/components/file_upload/` |
| Plain ERB | Full markup control (chat attachments, upload progress card, custom layouts) | `app/views/components/file_upload/` |
All three need `app/javascript/controllers/file_upload_controller.js`. It has no dependencies; `@rails/activestorage` is imported only when `auto_upload` is used.
## Installation
1. Copy `file_upload_controller.js` to `app/javascript/controllers/`. With importmap and `eagerLoadControllersFrom` / `pin_all_from` it registers itself as `file-upload`.
2. For the ViewComponent, copy `app/components/file_upload/` (needs the `view_component` gem, 4.x).
3. For the shared partial, copy `app/views/shared/components/file_upload/`.
4. For direct uploads: Active Storage installed, `ActiveStorage.start()` in your JavaScript, and CORS configured on your storage service.
5. Tailwind CSS v4.
## ViewComponent
### Basic Usage
```erb
<%= form_with model: @project do |form| %>
<%= render FileUpload::Component.new(
name: "project[documents]",
label: "Documents",
hint: "PDF, PNG or JPG. Up to 25 MB each.",
accept: "application/pdf,image/png,image/jpeg",
max_files: 10,
max_size: 25.megabytes,
direct_upload: true,
attachments: @project.documents,
error: @project.errors.full_messages_for(:documents).to_sentence
) %>
<%= form.submit %>
<% end %>
```
### Variants
| Variant | Use for | Multiple |
|---------|---------|----------|
| `:dropzone` (default) | Documents, attachments, anything; a drop area with a file list | yes (set `multiple: false` for one file) |
| `:button` | One file next to other fields: "Choose PDF" that turns into "Replace" | no (set `multiple: true` for several) |
| `:images` | Photo galleries: a grid of square thumbnails with an add tile | always |
| `:avatar` | Profile photos and logos: one round image with change and remove | never |
### Options
| Option | Default | Description |
|--------|---------|-------------|
| `name` | required | Input name, e.g. `"project[documents]"`. `[]` is added for multiple uploads |
| `label` | required | Visible label (the photo title for `:avatar`) |
| `variant` | `:dropzone` | `:dropzone`, `:button`, `:images` or `:avatar` |
| `id` | from `name` | Input id (`project_documents`) |
| `hint` | `nil` | Help text, linked with `aria-describedby` |
| `multiple` | per variant | Allow several files (`:images` is always multiple, `:avatar` never) |
| `accept` | `nil` (`"image/*"` for `:images` and `:avatar`) | Accepted types: `".pdf,image/*"`, `"application/pdf,image/png"` |
| `max_files` | `0` | Maximum number of files, counting existing attachments. 0 = no limit |
| `max_size` | `0` | Maximum bytes per file, e.g. `5.megabytes`. 0 = no limit |
| `required` | `false` | Require at least one file (existing attachments count) |
| `direct_upload` | `false` | Active Storage direct uploads with per-file progress on submit |
| `auto_upload` | `false` | Direct-upload each file as soon as it is added. Implies `direct_upload` |
| `attachments` | `[]` | Existing files: Active Storage attachments (`@project.documents`, `current_user.avatar`), or hashes with `:name`, `:signed_id` and optional `:size`, `:url`. Unsaved files are skipped |
| `error` | `nil` | Server-side error shown under the field; also sets `aria-invalid` |
| `classes` | `nil` | Extra classes for the wrapper |
| `html_options` | `{}` | Other wrapper attributes (`id`, `data`…). A `data: { controller: }` is combined with `file-upload` |
An unknown `variant` raises `ArgumentError`.
## Shared Partial
Same options as locals, same markup:
```erb
<%= render "shared/components/file_upload/file_upload",
variant: :avatar,
name: "user[avatar]",
label: "Profile photo",
hint: "PNG or JPG, 2 MB max.",
max_size: 2.megabytes,
attachments: current_user.avatar,
error: current_user.errors.full_messages_for(:avatar).to_sentence %>
```
## Plain ERB
```erb
<div data-controller="file-upload" data-file-upload-max-size-value="<%= 10.megabytes %>">
<%= form.file_field :documents, multiple: true, direct_upload: true, class: "sr-only", tabindex: -1,
data: { file_upload_target: "input" } %>
<div role="button" tabindex="0" data-file-upload-target="dropzone" aria-describedby="documents_hint"
class="rounded-xl border border-dashed p-8 text-center data-[drag=accept]:border-neutral-900 data-[drag=reject]:border-red-500">
Drop files here or browse
<p id="documents_hint">PDF, up to 10 MB each.</p>
</div>
<p data-file-upload-target="error" hidden class="text-xs text-red-600"></p>
<ul data-file-upload-target="list"></ul>
<template data-file-upload-target="template">
<li data-file-upload-target="item" class="group/file flex items-center gap-3">
<img data-file-upload-field="preview" alt="" class="size-10 object-cover">
<span data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 truncate"></span>
<span data-file-upload-field="size"></span>
<button type="button" data-action="file-upload#remove" data-file-upload-field="remove">×</button>
</li>
</template>
<p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
</div>
```
The examples in `app/views/components/file_upload/` cover: basic input, upload button, dropzone, validation, image grid, avatar, upload progress with Retry, and chat attachments with paste.
## Stimulus Controller
### Values
| Value | Default | Description |
|-------|---------|-------------|
| `data-file-upload-max-files-value` | `0` | Maximum files (multiple inputs only), counting server-rendered items |
| `data-file-upload-max-size-value` | `0` | Maximum bytes per file |
| `data-file-upload-accept-value` | input's `accept` | Accepted types |
| `data-file-upload-auto-upload-value` | `false` | Upload on pick; needs `data-direct-upload-url` on the input |
| `data-file-upload-messages-value` | `{}` | JSON overrides for the messages (see Translations) |
`multiple` comes from the input itself.
### Targets
- `input` (required): the real `<input type="file">`. Keep it in the form; hide it with `sr-only`, not `hidden` or `display: none`.
- `dropzone`: accepts drops; gets `data-drag="accept" | "reject"`. With `role="button"` and `tabindex="0"` it opens the picker on click, Enter and Space.
- `list` + `template`: the template's first element (an `item` target) is cloned into the list for each file.
- `item`: a file in the list. Server-rendered items count toward `max_files` and can be removed.
- `error`: validation and upload messages; render it `hidden`.
- `status`: `aria-live="polite"` region for announcements.
- `count`: receives the number of files.
### Item Fields
Elements inside an item with `data-file-upload-field`:
- `name`, `size`, `extension`, `percent`: text. `data-truncate="middle"` plus `flex` on `name` keeps the extension visible.
- `preview`: an `<img>` thumbnail for images (hidden for other files).
- `bar` (width) and `ring` (stroke-dashoffset on a `pathLength="100"` circle): progress.
- `error`: the upload error.
- `remove`, `retry`: buttons that get "Remove report.pdf" / "Retry report.pdf" labels.
### Actions
- `file-upload#open`: opens the picker (buttons; button-like dropzones don't need it).
- `file-upload#remove`: removes the item the button is in.
- `file-upload#clear`: removes every file.
- `file-upload#retry`: retries a failed upload (resubmits the form, or re-uploads the file with `auto_upload`).
- `file-upload#paste`: adds pasted files; bind to `paste` on a textarea or the whole element.
- From JavaScript: `controller.add(fileListOrArray)`.
### Events
| Event | `event.detail` | Notes |
|-------|----------------|-------|
| `file-upload:add` | `{ files, elements }` | After files pass validation and are listed |
| `file-upload:remove` | `{ file, element, replaced }` | Per removed item; `file` is `null` for server-rendered items |
| `file-upload:change` | `{ files }` | Whenever the files change, in list order |
| `file-upload:reject` | `{ errors }` | Validation failed |
| `file-upload:retry` | `{ file, element }` | Cancelable: `preventDefault()` to retry with your own uploader |
| `direct-upload:*` (listened) | `{ id, file, progress?, error? }` | `initialize`, `start`, `progress`, `error`, `end` on the input drive item states |
### Styling Hooks
- Controller element: `data-has-files`, `data-full` (at `max_files`), `data-uploading` (while the form's direct uploads run). Put `group/upload` on it and use `group-data-has-files/upload:hidden`, `group-data-full/upload:opacity-60`.
- Dropzone: `data-drag="accept" | "reject"`.
- Item: `data-state="idle" | "queued" | "uploading" | "success" | "error"` and `data-kind="image" | "pdf" | "doc" | "sheet" | "archive" | "video" | "audio" | "code" | "file"`. Put `group/file` on it: `group-data-[state=uploading]/file:opacity-100`.
## Existing Attachments
Assigning `has_many_attached` replaces the whole set, so each existing file is rendered as an item holding a hidden field with its `signed_id`; the files that stay are submitted again, and removing an item detaches that file. The ViewComponent and partial do this from `attachments:`. In plain ERB:
```erb
<input type="hidden" name="listing[photos][]" value="" autocomplete="off">
<%= form.file_field :photos, multiple: true, class: "sr-only", tabindex: -1, data: { file_upload_target: "input" } %>
<ul data-file-upload-target="list">
<% listing.photos.each do |photo| %>
<li data-file-upload-target="item">
<%= image_tag photo.variant(resize_to_fill: [320, 320]), alt: "" %>
<span data-file-upload-field="name" class="sr-only"><%= photo.filename %></span>
<%= hidden_field_tag "listing[photos][]", photo.signed_id, id: nil %>
<button type="button" data-action="file-upload#remove" aria-label="Remove <%= photo.filename %>">×</button>
</li>
<% end %>
</ul>
```
For `has_one_attached`: an empty hidden field before the input, the current `signed_id` field after it (inside the item). The last value wins: keeping, replacing and removing all work.
Strong params: `params.expect(project: [documents: []])` for many, `params.expect(user: [:avatar])` for one.
## Direct Uploads
- **On submit** (`direct_upload: true`): Active Storage uploads one file at a time and stops at the first error. Files are `queued`, then `uploading`; Remove, Clear and Retry are disabled meanwhile. Uploaded files leave the input and are kept by their `signed_id` field, so Retry only sends what failed or never started.
- **On pick** (`auto_upload: true`): three at a time. Removing a file cancels its upload. Submitting waits for running uploads, then submits; if one failed, the form stays put. Removed files leave unattached blobs: purge `ActiveStorage::Blob.unattached` in a scheduled job.
- **Custom uploaders**: dispatch `direct-upload:initialize`, `start`, `progress` (`detail.progress` 0–100), `error` (`detail.error`) and `end` on the input with `detail: { id, file }`. Insert a hidden field named like the input right before it, holding the result, before dispatching `end`.
## Translations
```js
import FileUpload from "controllers/file_upload_controller"
Object.assign(FileUpload.messages, {
type: "« %{name} » n’est pas un type de fichier accepté.",
size: "« %{name} » dépasse %{limit}.",
count: "Vous pouvez ajouter jusqu’à %{max} fichiers.",
count_one: "Vous ne pouvez ajouter qu’un fichier.",
added: "%{name} ajouté.", added_many: "%{count} fichiers ajoutés.",
removed: "%{name} supprimé.", uploaded: "%{name} envoyé.",
failed: "L’envoi a échoué.", failed_named: "%{name} : %{error}",
waiting: "Envoi des fichiers en cours…",
remove_label: "Supprimer %{name}", retry_label: "Réessayer %{name}",
units: "o Ko Mo Go",
})
```
Per element: `data-file-upload-messages-value='{"removed": "%{name} supprimé."}'`. Sizes use the number format of the nearest `lang` attribute. Text in your markup is translated with `t()` as usual.
## Accessibility
- The real input stays in the form with a `<label for>` (or `aria-label`); `required` works and its message is shown inline.
- Dropzones that open the picker are `role="button"` with `tabindex="0"`; openers get `aria-disabled="true"` when full or disabled and explain why when activated.
- Error targets are added to the `aria-describedby` of the input and openers; server errors set `aria-invalid`.
- Added, removed, uploaded and failed files are announced through the `status` target; removing a file moves focus to the next file or back to the picker.
- `role="progressbar"` elements are hidden from screen readers unless that file is uploading.
- Motion respects `prefers-reduced-motion`.
## Browser Support
Current Chrome, Edge, Firefox and Safari, on desktop and mobile. Syncing the input with the list needs `new DataTransfer()` (Chrome 60, Firefox 62, Safari 14.1); older browsers still pick and submit files, but removing one doesn't take it out of the input. HEIC previews only show in browsers that can display HEIC.
## Troubleshooting
- **Only the last file arrives**: the input name must end in `[]` and strong params need `documents: []`.
- **Saving removes existing files**: render them with `attachments:` (or `signed_id` hidden fields) so they are resubmitted.
- **Crash when re-rendering after a validation error**: `signed_id` was called on an unsaved file. The ViewComponent and partial skip those; in plain ERB, skip `attachment.blob.new_record?`.
- **No progress**: needs `direct_upload: true`, `ActiveStorage.start()` and CORS on the storage bucket.
- **Dropzone does nothing**: add `role="button"` and `tabindex="0"`, make sure the input isn't `disabled`, and read the console warnings.
- **Files picked, then lost after navigating back**: browsers never restore file inputs; the controller clears picked files before Turbo caches the page on purpose.
---
## AI Instructions
### Choose An Implementation
- **ViewComponent**: Default when the app has `view_component`. One call per field: pick a `variant`, pass `attachments:` and `error:` from the model.
- **Shared partial**: Use when the app has no ViewComponent. Identical options as locals.
- **Plain ERB**: Use for layouts the variants don't cover (chat composer chips, upload progress card, custom grids); copy the closest file from `app/views/components/file_upload/`.
### Quick Reference
- **Vanilla examples**: `app/views/components/file_upload/`
- **ERB partial files**: `app/views/shared/components/file_upload/`
- **ERB template**: `render "shared/components/file_upload/file_upload", name: "project[documents]", label: "Documents"`
- **ViewComponent**: `render FileUpload::Component.new(name: "project[documents]", label: "Documents")`
- **ViewComponent files**: `app/components/file_upload/`
- **Stimulus controller**: `app/javascript/controllers/file_upload_controller.js` (identifier `file-upload`)
### Implementation Checklist
- Use the model's param name: `name: "project[documents]"` for `has_many_attached :documents`, `name: "user[avatar]"` for `has_one_attached :avatar`.
- Permit arrays for many: `params.expect(project: [documents: []])`.
- Pass existing files: `attachments: @project.documents` / `attachments: current_user.avatar`, so saving keeps them.
- Pass server errors: `error: @project.errors.full_messages_for(:documents).to_sentence`, and render with `status: :unprocessable_entity` on failure.
- Mirror client limits in the model (content type and byte size); client checks are only a convenience.
- Use `direct_upload: true` for large files or progress bars; `auto_upload: true` when files should upload while the user fills the rest of the form.
- In plain ERB keep: the `input` target inside the form (`sr-only`, `tabindex="-1"`), `role="button"` + `tabindex="0"` on dropzones, a `<template>` whose first element is the `item` target, a hidden `error` target, and an `aria-live` `status` target.
### Common Patterns
- Document attachments: `:dropzone` with `accept`, `max_size`, `direct_upload: true`.
- Receipts / limited uploads: `:dropzone` with `max_files: 3`.
- Contract or résumé: `:button` with `accept: ".pdf"`.
- Product or listing photos: `:images` with `max_files: 8`, `attachments: @listing.photos`.
- Profile picture or logo: `:avatar` with `attachments: current_user.avatar`.
- Chat or comment composer: plain ERB from `_8_chat_attachments.html.erb` (paste screenshots, chips, Retry).
### Common Mistakes
- Do not hide the input with `hidden`, `display: none` or `disabled`; use `sr-only` so it submits and validates.
- Do not forget `[]` on multiple input names in plain ERB, or `documents: []` in strong params.
- Do not render existing attachments without their `signed_id` hidden field; saving would detach them.
- Do not call `signed_id` on unsaved attachments when re-rendering after a failed save.
- Do not invent options (`max_count:`, `preview:`, `variant: :gallery`); unknown variants raise `ArgumentError`.
- Do not mix ViewComponent options with `data-file-upload-*` attributes on the same field.
- Do not listen to `file-upload:change` to start uploads; use `file-upload:add` (change also fires on removal and reorder).