File Upload Shared Partial

Don't forget the Stimulus controller!
The shared partial still requires the file_upload_controller.js Stimulus controller to be installed. Copy the controller from the Installation section on this page.

1. Copy shared partial files

Download all 1 shared partial files as a ZIP file.

Download all files (ZIP)

After downloading, unzip and copy the file_upload/ folder to your app/views/shared/components/ directory.

Copy these files to your app/views/shared/components/file_upload/ directory:

2. Usage example

<%# ── 1. Dropzone: drop several files or browse. Each file gets a row with a thumbnail, its size and a remove button. %>
<%= render "shared/components/file_upload/file_upload",
  name: "project[files]",
  label: "Project files",
  hint: "Any file type, as many as you need." %>

<%# ── 2. Validation: up to three PDF, PNG or JPG files of 2 MB each. Validate again in your model. %>
<%= render "shared/components/file_upload/file_upload",
  name: "expense[receipts]",
  label: "Receipts",
  hint: "PDF, PNG or JPG. Up to 2 MB each.",
  accept: "application/pdf,image/png,image/jpeg",
  max_files: 3,
  max_size: 2.megabytes %>

<%# ── 3. Upload button for a single file. It turns into Replace once a file is chosen. %>
<%= render "shared/components/file_upload/file_upload",
  variant: :button,
  name: "deal[contract]",
  label: "Signed contract",
  hint: "PDF, up to 10 MB.",
  accept: ".pdf",
  max_size: 10.megabytes %>

<%# ── 4. Image grid with photos that are already attached. In your app: attachments: @listing.photos %>
<%= render "shared/components/file_upload/file_upload",
  variant: :images,
  name: "listing[photos]",
  label: "Listing photos",
  hint: "JPG, PNG or WebP. Up to 8 MB each.",
  max_files: 8,
  max_size: 8.megabytes,
  attachments: [
    { name: "watch-front.jpg", signed_id: "watch-front-signed-id", url: "https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=320&h=320&fit=crop&auto=format&q=80" },
    { name: "watch-detail.jpg", signed_id: "watch-detail-signed-id", url: "https://images.unsplash.com/photo-1524805444758-089113d48a6d?w=320&h=320&fit=crop&auto=format&q=80" }
  ] %>

<%# ── 5. Avatar with the current photo. In your app: attachments: current_user.avatar %>
<%= render "shared/components/file_upload/file_upload",
  variant: :avatar,
  name: "user[avatar]",
  label: "Profile photo",
  hint: "PNG, JPG, GIF or WebP. 2 MB max.",
  accept: "image/png,image/jpeg,image/gif,image/webp",
  max_size: 2.megabytes,
  attachments: { name: "avatar.jpg", signed_id: "current-avatar-signed-id", url: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=160&h=160&fit=crop&crop=face&auto=format&q=80" } %>

<%# ── 6. Active Storage direct uploads: each row shows its progress when the form submits, with Retry on errors. Use auto_upload: true instead to upload each file as soon as it is picked. %>
<%= render "shared/components/file_upload/file_upload",
  name: "launch[assets]",
  label: "Launch assets",
  max_size: 50.megabytes,
  direct_upload: true,
  attachments: [{ name: "press-kit.pdf", signed_id: "press-kit-signed-id", size: 2.4.megabytes }] %>

Rendered usage example

Drop files here or browse

Any file type, as many as you need.

0 of 3

Drop files here or browse

PDF, PNG or JPG. Up to 2 MB each.

No file chosen

PDF, up to 10 MB.

2 of 8

  • Add
  • watch-front.jpg
  • watch-detail.jpg

JPG, PNG or WebP. Up to 8 MB each.

Profile photo

PNG, JPG, GIF or WebP. 2 MB max.

Drop files here or browse

  • pdf

    press-kit.pdf

    2.4 MB

File Upload ViewComponent

Don't forget the Stimulus controller!
The ViewComponent still requires the file_upload_controller.js Stimulus controller to be installed. Copy the controller from the Installation section on this page.

1. Ensure the gem is installed

gem "view_component", "~> 4.2"

2. Copy component files

Download all 2 component files as a ZIP file.

Download all files (ZIP)

After downloading, unzip and copy the file_upload/ folder to your app/components/ directory.

Copy these files to your app/components/file_upload/ directory:

3. Usage example

<%# ── 1. Dropzone: drop several files or browse. Each file gets a row with a thumbnail, its size and a remove button. %>
<%= render FileUpload::Component.new(
  name: "project[files]",
  label: "Project files",
  hint: "Any file type, as many as you need."
) %>

<%# ── 2. Validation: up to three PDF, PNG or JPG files of 2 MB each. Validate again in your model. %>
<%= render FileUpload::Component.new(
  name: "expense[receipts]",
  label: "Receipts",
  hint: "PDF, PNG or JPG. Up to 2 MB each.",
  accept: "application/pdf,image/png,image/jpeg",
  max_files: 3,
  max_size: 2.megabytes
) %>

<%# ── 3. Upload button for a single file. It turns into Replace once a file is chosen. %>
<%= render FileUpload::Component.new(
  variant: :button,
  name: "deal[contract]",
  label: "Signed contract",
  hint: "PDF, up to 10 MB.",
  accept: ".pdf",
  max_size: 10.megabytes
) %>

<%# ── 4. Image grid with photos that are already attached. In your app: attachments: @listing.photos %>
<%= render FileUpload::Component.new(
  variant: :images,
  name: "listing[photos]",
  label: "Listing photos",
  hint: "JPG, PNG or WebP. Up to 8 MB each.",
  max_files: 8,
  max_size: 8.megabytes,
  attachments: [
    { name: "watch-front.jpg", signed_id: "watch-front-signed-id", url: "https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=320&h=320&fit=crop&auto=format&q=80" },
    { name: "watch-detail.jpg", signed_id: "watch-detail-signed-id", url: "https://images.unsplash.com/photo-1524805444758-089113d48a6d?w=320&h=320&fit=crop&auto=format&q=80" }
  ]
) %>

<%# ── 5. Avatar with the current photo. In your app: attachments: current_user.avatar %>
<%= render FileUpload::Component.new(
  variant: :avatar,
  name: "user[avatar]",
  label: "Profile photo",
  hint: "PNG, JPG, GIF or WebP. 2 MB max.",
  accept: "image/png,image/jpeg,image/gif,image/webp",
  max_size: 2.megabytes,
  attachments: { name: "avatar.jpg", signed_id: "current-avatar-signed-id", url: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=160&h=160&fit=crop&crop=face&auto=format&q=80" }
) %>

<%# ── 6. Active Storage direct uploads: each row shows its progress when the form submits, with Retry on errors. Use auto_upload: true instead to upload each file as soon as it is picked. %>
<%= render FileUpload::Component.new(
  name: "launch[assets]",
  label: "Launch assets",
  max_size: 50.megabytes,
  direct_upload: true,
  attachments: [{ name: "press-kit.pdf", signed_id: "press-kit-signed-id", size: 2.4.megabytes }]
) %>

Rendered usage example

Drop files here or browse

Any file type, as many as you need.

0 of 3

Drop files here or browse

PDF, PNG or JPG. Up to 2 MB each.

No file chosen

PDF, up to 10 MB.

2 of 8

  • Add
  • watch-front.jpg
  • watch-detail.jpg

JPG, PNG or WebP. Up to 8 MB each.

Profile photo

PNG, JPG, GIF or WebP. 2 MB max.

Drop files here or browse

  • pdf

    press-kit.pdf

    2.4 MB

File Upload Rails Components

File inputs, dropzones, image previews and attachment chips that enhance a real <input type="file">. Whatever is on screen is exactly what the form submits, so it works with plain Rails forms and with Active Storage direct uploads.

Installation

Stimulus Controller Setup

Add the controller to app/javascript/controllers/file_upload_controller.js. It has no dependencies. The first example is CSS only and doesn't need it.

import { Controller } from "@hotwired/stimulus";

// File Upload
//
// Enhances a real <input type="file"> so files can be dropped, pasted, previewed, validated
// and removed one by one, while the input's FileList always mirrors what is on screen.
// That means the files submit with a normal Rails form, and Active Storage direct uploads
// (`direct_upload: true`) keep working: the controller listens for the `direct-upload:*`
// events and reflects their progress on each file. Add data-file-upload-auto-upload-value="true"
// to upload each file as soon as it is picked instead of when the form submits.
//
// Every file is rendered by cloning the <template> target into the list target. The
// controller only fills in text, sets a few data attributes and animates; all styling
// lives in your markup:
//
//   on the controller element   data-has-files, data-full, data-uploading (while the form's direct uploads run)
//   on the dropzone target      data-drag="accept" | "reject"
//   on each item target         data-state="idle" | "queued" | "uploading" | "success" | "error"
//                               data-kind="image" | "pdf" | "doc" | "sheet" | "archive" | "video" | "audio" | "code" | "file"
//
// Inside an item, elements marked with data-file-upload-field are filled in:
//   name, size, extension, preview (an <img>), bar (width), ring (stroke-dashoffset on a
//   pathLength="100" circle), percent, error, remove and retry (get an aria-label with the file name)
//   Add data-truncate="middle" (and the `flex` class) to a name field to shorten long names in the
//   middle, so the extension stays visible: "quarterly-report-…-final.pdf".
//
// The input's files follow the order of the items in the list, so a sortable list reorders them too.
//
// Events (on the controller element): file-upload:add { files, elements }, file-upload:remove
// { file, element, replaced }, file-upload:change { files }, file-upload:reject { errors } and
// file-upload:retry { file, element } (cancelable). Any uploader can drive the item states by
// dispatching Active Storage's direct-upload:initialize/start/progress/error/end events on the input.
//
// Accessibility is handled for you: buttons that open the picker get aria-disabled while the
// list is full or the input is disabled, error targets are linked to the input and to those
// buttons with aria-describedby, and role="progressbar" elements inside an item are hidden from
// screen readers unless that file is uploading.

// User-facing copy. %{…} placeholders are filled in. Translate it once for the whole app with
//   import FileUpload from "controllers/file_upload_controller"
//   Object.assign(FileUpload.messages, { removed: "%{name} supprimé." })
// or per element with data-file-upload-messages-value='{"removed": "%{name} supprimé."}'.
const MESSAGES = {
  type: "“%{name}” isn’t a supported file type.",
  size: "“%{name}” is larger than %{limit}.",
  count: "You can add up to %{max} files.",
  count_one: "You can add only one file.",
  added: "Added %{name}.",
  added_many: "Added %{count} files.",
  removed: "Removed %{name}.",
  uploaded: "%{name} uploaded.",
  failed: "Upload failed.",
  failed_named: "%{name}: %{error}",
  waiting: "Waiting for uploads to finish…",
  remove_label: "Remove %{name}",
  retry_label: "Retry %{name}",
  units: "B KB MB GB",
};

const EXTENSION_KINDS = {
  pdf: "pdf",
  doc: "doc", docx: "doc", txt: "doc", rtf: "doc", md: "doc", pages: "doc",
  xls: "sheet", xlsx: "sheet", csv: "sheet", numbers: "sheet",
  zip: "archive", rar: "archive", "7z": "archive", tar: "archive", gz: "archive",
  js: "code", ts: "code", rb: "code", erb: "code", py: "code", html: "code", css: "code", json: "code",
};

// Some files arrive without a MIME type (.md, .heic on Windows, most types during a Safari drag),
// and `accept` treats .jpg and .jpeg as the same thing. This table fills those gaps.
const MIME_TYPES = {
  jpg: "image/jpeg", jpeg: "image/jpeg", jpe: "image/jpeg", png: "image/png", gif: "image/gif", webp: "image/webp",
  avif: "image/avif", svg: "image/svg+xml", heic: "image/heic", heif: "image/heif", tif: "image/tiff", tiff: "image/tiff",
  pdf: "application/pdf", txt: "text/plain", md: "text/markdown", csv: "text/csv", json: "application/json",
  htm: "text/html", html: "text/html", zip: "application/zip", mp4: "video/mp4", mov: "video/quicktime", webm: "video/webm",
  mp3: "audio/mpeg", wav: "audio/wav", m4a: "audio/mp4",
  doc: "application/msword", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  xls: "application/vnd.ms-excel", xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  ppt: "application/vnd.ms-powerpoint", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
};

const EASE_OUT = "cubic-bezier(0.23, 1, 0.32, 1)";

// How many files upload at the same time with autoUpload.
const UPLOAD_CONCURRENCY = 3;
let autoUploadId = 0;

// Loaded only when autoUpload is used, so the controller works without Active Storage.
let activeStorage;
const loadActiveStorage = () => (activeStorage ||= import("@rails/activestorage"));

const LOCKED_BUTTONS = ["remove", "clear", "retry"].map((action) => `button[data-action*='file-upload#${action}']`).join(", ");

// A file dropped a few pixels outside a dropzone would make the browser open it and throw away
// the form. While any file upload is on the page, such drops do nothing instead. Drops that
// another handler accepts (it called preventDefault) and native file inputs are left alone.
let pageGuards = 0;

const unhandledFileDrag = (event) =>
  !event.defaultPrevented && Array.from(event.dataTransfer?.types || []).includes("Files") && !event.target.closest?.("input[type='file']");

const guardPageDragOver = (event) => {
  if (!unhandledFileDrag(event)) return;
  event.preventDefault();
  event.dataTransfer.dropEffect = "none";
};

const guardPageDrop = (event) => {
  if (unhandledFileDrag(event)) event.preventDefault();
};

function guardPage(on) {
  pageGuards += on ? 1 : -1;
  if (on && pageGuards === 1) {
    window.addEventListener("dragover", guardPageDragOver);
    window.addEventListener("drop", guardPageDrop);
  } else if (!on && pageGuards === 0) {
    window.removeEventListener("dragover", guardPageDragOver);
    window.removeEventListener("drop", guardPageDrop);
  }
}

export default class extends Controller {
  static targets = ["input", "dropzone", "list", "template", "item", "error", "status", "count"];
  static values = {
    maxFiles: { type: Number, default: 0 }, // 0 = no limit (only applies to `multiple` inputs)
    maxSize: { type: Number, default: 0 }, // bytes, 0 = no limit
    accept: String, // falls back to the input's own `accept` attribute
    autoUpload: Boolean, // direct-upload each file as soon as it is added (needs `direct_upload: true` on the input)
    messages: Object, // overrides for MESSAGES, e.g. { "removed": "%{name} supprimé." }
  };

  static messages = MESSAGES;

  connect() {
    // Files picked in this session: { file, element, url, state, progress, directUploadId, signedIdInput, transfer, xhr }
    this.records = [];
    this.dragDepth = 0;
    this.element.addEventListener("direct-upload:initialize", this.onDirectUploadInitialize);
    this.element.addEventListener("direct-upload:start", this.onDirectUploadStart);
    this.element.addEventListener("direct-upload:progress", this.onDirectUploadProgress);
    this.element.addEventListener("direct-upload:error", this.onDirectUploadError);
    this.element.addEventListener("direct-upload:end", this.onDirectUploadEnd);
    document.addEventListener("turbo:before-cache", this.onBeforeCache);
    guardPage(true);
    this.describeErrors();
    this.refresh();
    this.checkSetup();
  }

  disconnect() {
    this.listObserver?.disconnect();
    this.element.removeEventListener("direct-upload:initialize", this.onDirectUploadInitialize);
    this.element.removeEventListener("direct-upload:start", this.onDirectUploadStart);
    this.element.removeEventListener("direct-upload:progress", this.onDirectUploadProgress);
    this.element.removeEventListener("direct-upload:error", this.onDirectUploadError);
    this.element.removeEventListener("direct-upload:end", this.onDirectUploadEnd);
    document.removeEventListener("turbo:before-cache", this.onBeforeCache);
    guardPage(false);
    this.reset();
  }

  inputTargetConnected(input) {
    input.addEventListener("change", this.onInputChange);
    input.addEventListener("invalid", this.onInvalid);
    if (this.autoUploadValue && !input.dataset.directUploadUrl) {
      console.warn("file-upload: autoUpload needs an input with direct_upload: true (data-direct-upload-url). Files will upload when the form submits.", input);
    }
    this.required = input.required;
    this.form = input.form;
    this.form?.addEventListener("reset", this.onFormReset);
    this.form?.addEventListener("submit", this.onSubmit);
    this.form?.addEventListener("direct-uploads:start", this.onDirectUploadsStart);
    this.form?.addEventListener("direct-uploads:end", this.onDirectUploadsEnd);
  }

  inputTargetDisconnected(input) {
    input.removeEventListener("change", this.onInputChange);
    input.removeEventListener("invalid", this.onInvalid);
    if (this.required) input.required = true;
    this.form?.removeEventListener("reset", this.onFormReset);
    this.form?.removeEventListener("submit", this.onSubmit);
    this.form?.removeEventListener("direct-uploads:start", this.onDirectUploadsStart);
    this.form?.removeEventListener("direct-uploads:end", this.onDirectUploadsEnd);
    this.form = null;
  }

  // Watches for items being moved (by a sortable list, for example) and reorders the input to match.
  listTargetConnected(list) {
    this.listObserver?.disconnect();
    this.listObserver = new MutationObserver(() => this.syncIfReordered());
    this.listObserver.observe(list, { childList: true, subtree: true });
  }

  listTargetDisconnected() {
    this.listObserver?.disconnect();
    this.listObserver = null;
  }

  // Server-rendered items get the same name treatment as the ones built from the template.
  itemTargetConnected(item) {
    this.fields(item, "name").forEach((field) => {
      if (field.dataset.truncate === "middle" && field.childElementCount === 0) this.writeName(field, field.textContent.trim());
    });
  }

  dropzoneTargetConnected(dropzone) {
    // A dropzone that is a button (or has role="button") opens the picker on click, Enter and Space
    // without any data-action. Dropzones that already wire file-upload#open themselves are left alone.
    if (dropzone.matches("button, [role='button']") && !(dropzone.dataset.action || "").includes("file-upload#open")) {
      dropzone.addEventListener("click", this.onDropzoneActivate);
      dropzone.addEventListener("keydown", this.onDropzoneActivate);
    }
    dropzone.addEventListener("dragenter", this.onDragEnter);
    dropzone.addEventListener("dragover", this.onDragOver);
    dropzone.addEventListener("dragleave", this.onDragLeave);
    dropzone.addEventListener("drop", this.onDrop);
  }

  dropzoneTargetDisconnected(dropzone) {
    dropzone.removeEventListener("click", this.onDropzoneActivate);
    dropzone.removeEventListener("keydown", this.onDropzoneActivate);
    dropzone.removeEventListener("dragenter", this.onDragEnter);
    dropzone.removeEventListener("dragover", this.onDragOver);
    dropzone.removeEventListener("dragleave", this.onDragLeave);
    dropzone.removeEventListener("drop", this.onDrop);
  }

  // ---------------------------------------------------------------------------
  // Actions
  // ---------------------------------------------------------------------------

  // Opens the native file picker. Use on a button, or on a dropzone with
  // data-action="click->file-upload#open keydown.enter->file-upload#open keydown.space->file-upload#open:prevent"
  open(event) {
    if (this.inputTarget.disabled) return;

    if (event) {
      const origin = event.target.closest("button, a, input, label, [data-file-upload-target~='item']");
      const nested = origin && origin !== event.currentTarget && event.currentTarget.contains(origin);
      // Ignore clicks on things inside a dropzone (remove buttons, file rows) and key presses that bubbled up.
      if (nested || (event.type === "keydown" && event.target !== event.currentTarget)) return;
    }

    if (this.element.hasAttribute("data-full")) {
      // The button stays focusable (aria-disabled, not disabled) so it can say why nothing happens.
      const message = this.countMessage;
      this.reflow(() => this.showError([message]));
      return this.reject([message]);
    }

    this.inputTarget.click();
  }

  // data-action="paste->file-upload#paste" on a textarea (or the whole element)
  paste(event) {
    const files = event.clipboardData?.files;
    if (!files?.length) return; // plain text paste, leave it alone
    // Excel, Numbers, Word and Pages put a picture of the selection on the clipboard next to the
    // text. They always add RTF, so when it's there the text is what the user meant to paste.
    if (Array.from(event.clipboardData.types || []).includes("text/rtf")) return;

    event.preventDefault();
    if (this.inputTarget.disabled) return;
    this.add(files);
  }

  remove(event) {
    const item = event.target.closest("[data-file-upload-target~='item']");
    if (!item || this.uploading) return; // a file can't be taken back while the form is uploading it

    const field = item.querySelector("[data-file-upload-field~='name']");
    const name = this.recordFor(item)?.file.name || field?.title || field?.textContent?.trim();
    const neighbour = this.itemTargets[this.itemTargets.indexOf(item) + 1] || this.itemTargets[this.itemTargets.indexOf(item) - 1];

    this.discard(item);
    this.sync();
    if (name) this.announce(this.t("removed", { name }));

    // Keep keyboard users in place: next file's first button, otherwise whatever opens the picker.
    const fallback = this.hasDropzoneTarget && this.dropzoneTarget.tabIndex >= 0 ? this.dropzoneTarget : this.element.querySelector("[data-action*='file-upload#open']");
    (neighbour?.querySelector("button") || fallback)?.focus({ preventScroll: true });
  }

  clear() {
    if (this.uploading) return;

    this.discard(this.itemTargets);
    this.sync();
    // The button that triggered this may hide itself now, so hand focus back to the picker button.
    this.element.querySelector("[data-action*='file-upload#open']")?.focus({ preventScroll: true });
  }

  // Uploads a failed file again: on its own with autoUpload, otherwise by resubmitting the form.
  // Files that already uploaded have left the input (their signed id stays in the form), so only
  // the failed file and the ones queued behind it are sent again. A custom uploader can listen for
  // "file-upload:retry" and call event.preventDefault() to handle the retry itself.
  retry(event) {
    const record = this.recordFor(event.target.closest("[data-file-upload-target~='item']"));
    if (!record || this.uploading) return;

    const retry = this.dispatch("retry", { detail: { file: record.file, element: record.element }, cancelable: true });
    if (retry.defaultPrevented) return;
    if (this.autoUploading) {
      this.enqueue(record);
      this.sync();
      this.pump();
    } else {
      this.inputTarget.form?.requestSubmit();
    }
  }

  // ---------------------------------------------------------------------------
  // Adding and removing files
  // ---------------------------------------------------------------------------

  // Public: validates files and adds the ones that pass. Accepts a FileList or an array.
  add(files) {
    let candidates = Array.from(files);
    const errors = [];

    if (!this.multiple) candidates = candidates.slice(0, 1);

    let accepted = candidates.filter((file) => {
      const error = this.validate(file);
      if (error) errors.push(error);
      return !error;
    });

    if (this.multiple) {
      // Picking the same file twice is a no-op, not an error.
      accepted = accepted.filter((file) => !this.records.some((record) => this.sameFile(record.file, file)));

      if (this.maxFilesValue > 0) {
        const room = Math.max(this.maxFilesValue - this.count, 0);
        if (accepted.length > room) {
          accepted = accepted.slice(0, room);
          errors.push(this.countMessage);
        }
      }
    }

    const records = accepted.map((file) => this.build(file));

    // Everything that changes the layout happens in one step, so the list, the empty state,
    // the error message and the container's height all animate together instead of jumping.
    this.reflow(() => {
      if (!this.multiple && records.length > 0) {
        // A single-file input replaces whatever was there.
        this.discard(this.itemTargets, { replaced: true });
        this.records.forEach((record) => this.release(record));
        this.records = [];
      }

      records.forEach((record) => record.element && this.listTarget.append(record.element));
      this.records.push(...records);
      this.showError(errors);
      this.refresh();
    });

    records.forEach((record, index) => this.enter(record.element, index));
    if (records.length > 0) {
      this.announce(records.length === 1 ? this.t("added", { name: records[0].file.name }) : this.t("added_many", { count: records.length }));
      this.dispatch("add", { detail: { files: records.map((record) => record.file), elements: records.map((record) => record.element).filter(Boolean) } });
    }

    if (this.autoUploading) records.forEach((record) => this.enqueue(record));
    this.sync();
    if (this.autoUploading) this.pump();
    if (errors.length > 0) this.reject(errors);
  }

  validate(file) {
    if (!this.accepts(file)) return this.t("type", { name: file.name });
    if (this.maxSizeValue > 0 && file.size > this.maxSizeValue) return this.t("size", { name: file.name, limit: this.formatBytes(this.maxSizeValue) });
    return null;
  }

  // Mirrors the browser's `accept` matching: ".pdf", "image/*" and "image/png" tokens.
  // A missing MIME type is looked up from the extension, and ".jpg" also accepts "photo.jpeg".
  // During a drag there is no name and often no type yet: anything unknown gets the benefit of
  // the doubt, and is checked properly once it is dropped.
  accepts({ name, type }) {
    const tokens = (this.acceptValue || this.inputTarget.accept || "").split(",").map((token) => token.trim().toLowerCase()).filter(Boolean);
    if (tokens.length === 0) return true;

    const lowerName = (name || "").toLowerCase();
    const extension = lowerName.includes(".") ? lowerName.split(".").pop() : "";
    const mime = (type || MIME_TYPES[extension] || "").toLowerCase();
    if (!name && !mime) return true;

    return tokens.some((token) => {
      if (token.startsWith(".")) return name ? lowerName.endsWith(token) || (mime !== "" && MIME_TYPES[token.slice(1)] === mime) : true;
      if (token.endsWith("/*")) return mime.startsWith(token.slice(0, -1));
      return mime === token;
    });
  }

  // Creates the record and its list item from the <template>.
  build(file) {
    const record = { file, element: null, url: null, state: "idle", progress: 0 };
    if (!this.hasTemplateTarget || !this.hasListTarget) return record;

    const element = this.templateTarget.content.firstElementChild.cloneNode(true);
    const extension = file.name.includes(".") ? file.name.split(".").pop().toLowerCase() : "";
    record.element = element;
    element.dataset.state = "idle";
    element.dataset.kind = this.kindOf(file, extension);

    this.fields(element, "name").forEach((field) => this.writeName(field, file.name));
    this.fields(element, "size").forEach((field) => (field.textContent = this.formatBytes(file.size)));
    this.fields(element, "extension").forEach((field) => (field.textContent = (extension || "file").slice(0, 4)));
    this.fields(element, "remove").forEach((field) => field.setAttribute("aria-label", this.t("remove_label", { name: file.name })));
    this.fields(element, "retry").forEach((field) => field.setAttribute("aria-label", this.t("retry_label", { name: file.name })));
    this.progressBars(element).forEach((bar) => bar.setAttribute("aria-hidden", "true"));

    this.fields(element, "preview").forEach((image) => {
      if (!file.type.startsWith("image/")) return (image.hidden = true);

      record.url ||= URL.createObjectURL(file);
      image.decoding = "async"; // big photos decode off the main thread, so adding them doesn't stutter
      image.src = record.url;
      // Some image formats (HEIC, for example) can't be rendered by every browser.
      image.addEventListener("error", () => {
        image.hidden = true;
        element.dataset.kind = "file";
      }, { once: true });
    });

    return record;
  }

  // Fills a name field. With data-truncate="middle" the name is split in two: the start shrinks
  // with an ellipsis and the end (the last few characters and the extension) always shows.
  // Screen readers get the full name once, from a visually hidden copy.
  writeName(field, name) {
    field.title = name;
    const extension = name.includes(".") ? name.slice(name.lastIndexOf(".")) : "";
    const tail = Math.min(extension.length + 5, 16);
    if (field.dataset.truncate !== "middle" || name.length <= tail + 3) return (field.textContent = name);

    const start = document.createElement("span");
    const end = document.createElement("span");
    const full = document.createElement("span");
    start.textContent = name.slice(0, -tail);
    end.textContent = name.slice(-tail);
    full.textContent = name;
    start.setAttribute("aria-hidden", "true");
    end.setAttribute("aria-hidden", "true");
    start.style.cssText = "min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: pre;";
    end.style.cssText = "flex-shrink: 0; white-space: pre;";
    full.style.cssText = "position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap;";
    field.replaceChildren(start, end, full);
  }

  // Removes items from the list. Works for picked files and for server-rendered items.
  discard(items, { replaced = false } = {}) {
    items = [].concat(items);

    // Stop counting them as files right away, then let them animate out.
    items.forEach((item) => {
      const record = this.recordFor(item);
      this.dispatch("remove", { detail: { file: record?.file || null, element: item, replaced } });
      if (record) {
        this.records = this.records.filter((other) => other !== record);
        this.release(record);
      }
      item.removeAttribute("data-file-upload-target");
      // Its signed_id field must not be submitted while the item animates out.
      item.querySelectorAll("input").forEach((field) => (field.disabled = true));
    });

    const overlaid = (item) => getComputedStyle(item).position === "absolute";
    const instant = (item) => this.reducedMotion || !this.hasListTarget || (replaced && !overlaid(item));
    const leaving = items.filter((item) => !instant(item));

    // Take each item out of the flow where it stands so its neighbours can slide into the gap while it fades.
    const geometry = leaving.map((item) => {
      const list = item.parentElement;
      if (getComputedStyle(list).position === "static") list.style.position = "relative";
      return { item, overlay: overlaid(item), top: item.offsetTop, left: item.offsetLeft, width: item.offsetWidth, height: item.offsetHeight };
    });

    this.reflow(() => {
      items.filter(instant).forEach((item) => item.remove());
      geometry.forEach(({ item, overlay, top, left, width, height }) => {
        if (overlay) return; // already out of the flow
        Object.assign(item.style, { position: "absolute", top: `${top}px`, left: `${left}px`, width: `${width}px`, height: `${height}px`, margin: "0" });
      });
      geometry.forEach(({ item }) => (item.style.pointerEvents = "none"));
      this.showError([]);
      this.refresh();
    });

    geometry.forEach(({ item }) => {
      const exit = item.animate([{ opacity: 1, transform: "scale(1)" }, { opacity: 0, transform: "scale(0.95)" }], { duration: 160, easing: "ease-out", fill: "forwards" });
      exit.finished.then(() => item.remove(), () => item.remove());
      setTimeout(() => item.remove(), 400); // animations pause in background tabs; never leave a ghost behind
    });
  }

  // Drops every picked file (form reset, Turbo cache). Server-rendered items stay.
  reset() {
    this.records.forEach((record) => {
      this.release(record);
      record.element?.remove();
    });
    this.records = [];
    this.showError([]);
    this.dropzoneTargets.forEach((dropzone) => delete dropzone.dataset.drag);
    this.refresh();
  }

  release(record) {
    record.xhr?.abort(); // an autoUpload still in flight
    record.xhr = null;
    record.transfer = null;
    if (record.url) URL.revokeObjectURL(record.url);
    record.url = null;
    // A file that was already direct-uploaded is attached through this hidden field, so
    // removing the file from the list must remove the field too.
    record.signedIdInput?.remove();
    record.signedIdInput = null;
  }

  // Writes the current files back into the real input, in list order, so the form submits exactly
  // what is listed. Files that were already direct-uploaded are left out (their signed id is in the
  // form instead), and so are files an autoUpload is still sending.
  sync() {
    const records = this.orderedRecords;
    if (this.hasInputTarget && typeof DataTransfer !== "undefined") {
      const transfer = new DataTransfer();
      records.filter((record) => !record.signedIdInput && !record.transfer).forEach((record) => transfer.items.add(record.file));
      this.inputTarget.files = transfer.files;
    }

    this.syncedFiles = records.map((record) => record.file);
    this.refresh();
    this.dispatch("change", { detail: { files: this.syncedFiles } });
    this.resumeSubmit(); // a file removed mid-upload may have been the last one the form was waiting for
  }

  // Called when the list changes. Adding and removing already sync; this only catches items that moved.
  syncIfReordered() {
    const files = this.orderedRecords.map((record) => record.file);
    const synced = this.syncedFiles || [];
    const sameFiles = files.length === synced.length && files.every((file) => synced.includes(file));
    if (sameFiles && files.some((file, index) => file !== synced[index])) this.sync();
  }

  refresh() {
    const count = this.count;
    // A required input is satisfied by any listed file, including server-rendered ones
    // that aren't in the input (an existing attachment, a file that already direct-uploaded).
    if (this.required && this.hasInputTarget) this.inputTarget.required = count === 0;
    this.element.toggleAttribute("data-has-files", count > 0);
    this.element.toggleAttribute("data-full", this.multiple && this.maxFilesValue > 0 && count >= this.maxFilesValue);
    this.countTargets.forEach((target) => (target.textContent = count));

    const unavailable = this.element.hasAttribute("data-full") || (this.hasInputTarget && this.inputTarget.disabled);
    this.openers.forEach((opener) => {
      if (unavailable) opener.setAttribute("aria-disabled", "true");
      else opener.removeAttribute("aria-disabled");
    });
  }

  // Links every error target to the input and to the buttons that open the picker, so a screen
  // reader reads the current error when one of them is focused. An empty error adds nothing.
  describeErrors() {
    if (!this.hasInputTarget) return;

    this.errorTargets.forEach((error, index) => {
      const base = this.inputTarget.id || `file_upload_${Math.random().toString(36).slice(2, 8)}`;
      error.id ||= `${base}_error${index > 0 ? `_${index}` : ""}`;
      [this.inputTarget, ...this.openers].forEach((control) => {
        const ids = (control.getAttribute("aria-describedby") || "").split(/\s+/).filter(Boolean);
        if (!ids.includes(error.id)) control.setAttribute("aria-describedby", [...ids, error.id].join(" "));
      });
    });
  }

  // ---------------------------------------------------------------------------
  // Feedback
  // ---------------------------------------------------------------------------

  // Writes the error text (or hides the element when there is none). Call inside reflow() so it animates.
  showError(errors) {
    const message = [...new Set(errors)].join(" ");
    this.errorTargets.forEach((target) => {
      target.textContent = message;
      target.hidden = message === "";
    });
    // A server-side error (aria-invalid from the form) is resolved once the user changes the files.
    if (this.hasInputTarget) {
      if (message) this.inputTarget.setAttribute("aria-invalid", "true");
      else this.inputTarget.removeAttribute("aria-invalid");
    }
  }

  reject(errors) {
    const messages = [...new Set(errors)];

    if (!this.reducedMotion) {
      this.errorTargets.forEach((target) => target.animate([{ opacity: 0, transform: "translateY(-4px)" }, { opacity: 1, transform: "translateY(0)" }], { duration: 200, easing: EASE_OUT }));
    }

    // A short horizontal shake reads as "no" without needing to read the message first.
    if (this.hasDropzoneTarget && !this.reducedMotion) {
      this.dropzoneTarget.animate({ transform: ["translateX(0)", "translateX(-5px)", "translateX(4px)", "translateX(-2px)", "translateX(0)"] }, { duration: 320, easing: "ease-out" });
    }

    this.announce(messages.join(" "));
    this.dispatch("reject", { detail: { errors: messages } });
  }

  announce(message) {
    if (this.hasStatusTarget) this.statusTarget.textContent = message;
  }

  setState(record, state, error = "") {
    record.state = state;
    if (!record.element) return;

    // The error line can change the row's height, so let the rows below slide instead of jump.
    this.reflow(() => {
      record.element.dataset.state = state;
      this.fields(record.element, "error").forEach((field) => (field.textContent = error));
    });
    this.progressBars(record.element).forEach((bar) => bar.setAttribute("aria-hidden", state === "uploading" ? "false" : "true"));
  }

  setProgress(record, progress) {
    record.progress = Math.max(0, Math.min(100, progress));
    if (!record.element) return;

    const rounded = Math.round(record.progress);
    this.fields(record.element, "bar").forEach((bar) => (bar.style.width = `${record.progress}%`));
    this.fields(record.element, "ring").forEach((ring) => (ring.style.strokeDashoffset = 100 - record.progress));
    this.fields(record.element, "percent").forEach((field) => (field.textContent = `${rounded}%`));
    record.element.querySelectorAll("[role='progressbar']").forEach((bar) => bar.setAttribute("aria-valuenow", rounded));
  }

  // ---------------------------------------------------------------------------
  // Motion (Web Animations API; movement is skipped for prefers-reduced-motion)
  // ---------------------------------------------------------------------------

  enter(element, index = 0) {
    if (!element) return;

    // Reduced motion keeps the fade (it helps to see what changed) but drops the movement.
    const from = this.reducedMotion ? { opacity: 0 } : { opacity: 0, transform: "translateY(6px) scale(0.97)" };
    const to = this.reducedMotion ? { opacity: 1 } : { opacity: 1, transform: "translateY(0) scale(1)" };

    element.animate([from, to], {
      duration: 260,
      delay: Math.min(index, 5) * 35,
      easing: EASE_OUT,
      fill: "backwards",
    });
  }

  // FLIP: remembers where everything in the list is, applies a DOM change, then animates the
  // children (and the container's height) from the old layout to the new one. Works for rows,
  // grids and chips, and for anything outside the list that the change shows or hides
  // (an empty state, an error message). Nested calls just run their change.
  reflow(change) {
    if (this.reflowing || !this.hasListTarget || this.reducedMotion) return change();

    this.reflowing = true;
    try {
      const element = this.element;
      const children = () => Array.from(this.listTarget.children).filter((child) => child.getClientRects().length > 0);
      const before = new Map(children().map((child) => [child, child.getBoundingClientRect()]));
      const heightBefore = element.getBoundingClientRect().height;

      change();

      const options = { duration: 240, easing: EASE_OUT };
      const heightAfter = element.getBoundingClientRect().height;
      if (Math.abs(heightBefore - heightAfter) > 0.5) {
        // Clip while the height catches up so rows that have already left (or not yet arrived) don't spill out.
        element.animate({ height: [`${heightBefore}px`, `${heightAfter}px`], overflow: ["clip", "clip"], overflowClipMargin: ["8px", "8px"] }, options);
      }

      before.forEach((from, child) => {
        if (!child.isConnected || child.style.position === "absolute") return;
        const to = child.getBoundingClientRect();
        const x = from.left - to.left;
        const y = from.top - to.top;
        if (x || y) child.animate({ transform: [`translate(${x}px, ${y}px)`, "translate(0, 0)"] }, options);
      });
    } finally {
      this.reflowing = false;
    }
  }

  // ---------------------------------------------------------------------------
  // Drag and drop
  // ---------------------------------------------------------------------------

  onDropzoneActivate = (event) => {
    if (event.type === "keydown") {
      if (event.key !== "Enter" && event.key !== " ") return;
      if (event.target !== event.currentTarget) return; // a key press inside, on a remove button for example
      event.preventDefault(); // Space would scroll the page, Enter would also click a <button>
    }
    this.open(event);
  };

  onDragEnter = (event) => {
    if (!this.carriesFiles(event) || this.inputTarget.disabled) return;

    event.preventDefault();
    this.dragDepth += 1;

    const dragged = Array.from(event.dataTransfer.items || []).filter((item) => item.kind === "file");
    const full = this.element.hasAttribute("data-full");
    const supported = dragged.length === 0 || dragged.some((item) => this.accepts({ type: item.type }));
    event.currentTarget.dataset.drag = full || !supported ? "reject" : "accept";
  };

  onDragOver = (event) => {
    if (!this.carriesFiles(event) || this.inputTarget.disabled) return;

    event.preventDefault(); // required, otherwise the browser never fires `drop`
    event.dataTransfer.dropEffect = event.currentTarget.dataset.drag === "reject" ? "none" : "copy";
  };

  onDragLeave = (event) => {
    if (!this.carriesFiles(event)) return;

    // dragenter/dragleave fire for every child element, so count them instead of trusting one event.
    this.dragDepth = Math.max(this.dragDepth - 1, 0);
    if (this.dragDepth === 0) delete event.currentTarget.dataset.drag;
  };

  onDrop = (event) => {
    if (!this.carriesFiles(event)) return;

    event.preventDefault();
    this.dragDepth = 0;
    delete event.currentTarget.dataset.drag;
    if (!this.inputTarget.disabled) this.add(event.dataTransfer.files);
  };

  carriesFiles(event) {
    return Array.from(event.dataTransfer?.types || []).includes("Files");
  }

  // ---------------------------------------------------------------------------
  // Native input
  // ---------------------------------------------------------------------------

  // The browser has just replaced the input's FileList with the new selection.
  // add() merges it with the files already listed and writes the result back.
  onInputChange = () => this.add(this.inputTarget.files);

  onFormReset = () => this.reset();

  // The input is visually hidden, so the browser's "Please select a file" bubble would point at
  // nothing. Show the browser's own (translated) message inline instead, and move focus to
  // whatever opens the picker if this is the first invalid field in the form.
  onInvalid = (event) => {
    event.preventDefault();
    this.reflow(() => this.showError([this.inputTarget.validationMessage]));
    this.reject([this.inputTarget.validationMessage]);

    const firstInvalid = Array.from(this.inputTarget.form?.elements || []).find((element) => element.willValidate && !element.validity.valid);
    if (firstInvalid !== this.inputTarget) return;

    const opener = this.hasDropzoneTarget && this.dropzoneTarget.tabIndex >= 0 ? this.dropzoneTarget : this.element.querySelector("[data-action*='file-upload#open']");
    opener?.focus();
  };

  // Turbo snapshots the page before it leaves. Picked files can't be restored (a file input
  // always comes back empty), so they are taken out first. Server-rendered items stay.
  onBeforeCache = () => this.reset();

  // ---------------------------------------------------------------------------
  // Active Storage direct uploads (https://guides.rubyonrails.org/active_storage_overview.html#direct-uploads)
  // These events only fire when the input has `direct_upload: true` and the form submits.
  // Active Storage initializes every file up front but uploads them one at a time and stops
  // at the first error, so a file only counts as uploading once its own upload starts.
  // ---------------------------------------------------------------------------

  onDirectUploadsStart = () => {
    this.element.toggleAttribute("data-uploading", true);
    // Remove, Clear and Retry can't change anything mid-upload, so they are disabled until it ends.
    this.lockedButtons = Array.from(this.element.querySelectorAll(LOCKED_BUTTONS)).filter((button) => !button.disabled);
    this.lockedButtons.forEach((button) => (button.disabled = true));
    this.refresh(); // Active Storage has disabled the input by now
  };

  onDirectUploadsEnd = () => {
    this.element.toggleAttribute("data-uploading", false);
    this.lockedButtons?.forEach((button) => (button.disabled = false));
    this.lockedButtons = null;
    this.refresh();
    // Active Storage stops at the first error, so files queued behind it go back to idle.
    this.records.filter((record) => ["queued", "uploading"].includes(record.state) && !record.transfer).forEach((record) => {
      this.setState(record, "idle");
      this.setProgress(record, 0);
    });
  };

  onDirectUploadInitialize = ({ detail }) => {
    const record = this.records.find((other) => other.file === detail.file);
    if (!record) return;

    record.directUploadId = detail.id;
    this.setState(record, "queued"); // its upload starts once the ones ahead of it are done
    this.setProgress(record, 0);
  };

  onDirectUploadStart = ({ detail }) => {
    const record = this.records.find((other) => other.directUploadId === detail.id);
    if (record) this.setState(record, "uploading");
  };

  onDirectUploadProgress = ({ detail }) => {
    const record = this.records.find((other) => other.directUploadId === detail.id);
    if (!record) return;

    if (record.state !== "uploading") this.setState(record, "uploading"); // uploaders that skip `start`
    this.setProgress(record, detail.progress);
  };

  onDirectUploadError = (event) => {
    const record = this.records.find((other) => other.directUploadId === event.detail.id);
    if (!record) return;

    event.preventDefault(); // replaces Active Storage's default alert() with the inline error
    this.fail(record, event.detail.error || this.t("failed"));
  };

  onDirectUploadEnd = ({ detail, target }) => {
    const record = this.records.find((other) => other.directUploadId === detail.id);
    if (!record || record.state === "error") return;

    // Active Storage has just written the blob's signed id into a hidden field it inserted
    // right before the input. Keep hold of it and take the file out of the input, so a retry
    // doesn't upload (and attach) this file a second time, and removing the row detaches it.
    const hidden = target.previousElementSibling;
    if (hidden?.type === "hidden" && hidden.name === target.name && hidden.value && !this.records.some((other) => other.signedIdInput === hidden)) {
      record.signedIdInput = hidden;
      this.sync();
    }

    this.succeed(record);
  };

  // ---------------------------------------------------------------------------
  // autoUpload: each file is direct-uploaded as soon as it is added, a few at a time. It reports
  // through the same direct-upload:* events Active Storage uses, so everything above (and your own
  // listeners) works the same way, and the signed id lands in the same hidden field.
  // ---------------------------------------------------------------------------

  enqueue(record) {
    record.transfer = "queued";
    record.directUploadId = `auto-${++autoUploadId}`;
    this.emit("initialize", record);
  }

  pump() {
    const active = this.records.filter((record) => record.transfer === "active").length;
    const room = Math.max(UPLOAD_CONCURRENCY - active, 0);
    this.records.filter((record) => record.transfer === "queued").slice(0, room).forEach((record) => this.upload(record));
  }

  async upload(record) {
    record.transfer = "active";
    const id = record.directUploadId;
    const current = () => this.records.includes(record) && record.directUploadId === id; // not removed or retried meanwhile
    this.emit("start", record);

    let DirectUpload;
    try {
      ({ DirectUpload } = await loadActiveStorage());
    } catch (error) {
      return this.uploaded(record, "Active Storage couldn’t be loaded.", current);
    }
    if (!current()) return;

    const watch = (xhr) => {
      record.xhr = xhr;
      xhr.upload.addEventListener("progress", (event) => {
        if (event.lengthComputable && current()) this.emit("progress", record, { progress: (event.loaded / event.total) * 100 });
      });
    };
    const upload = new DirectUpload(record.file, this.inputTarget.dataset.directUploadUrl, {
      directUploadWillCreateBlobWithXHR: (xhr) => (record.xhr = xhr),
      directUploadWillStoreFileWithXHR: watch,
    });
    upload.create((error, blob) => this.uploaded(record, error, current, blob));
  }

  uploaded(record, error, current, blob) {
    if (!current()) return;
    record.xhr = null;
    record.transfer = null;

    if (error) {
      this.emit("error", record, { error: String(error) });
      this.emit("end", record);
      this.sync(); // back in the input, so submitting the form tries it once more
    } else {
      // Same hidden field Active Storage adds for form direct uploads; onDirectUploadEnd claims it.
      const hidden = Object.assign(document.createElement("input"), { type: "hidden", name: this.inputTarget.name, value: blob.signed_id });
      this.inputTarget.insertAdjacentElement("beforebegin", hidden);
      this.emit("end", record);
    }

    this.pump();
    this.resumeSubmit();
  }

  emit(name, record, detail = {}) {
    this.inputTarget.dispatchEvent(new CustomEvent(`direct-upload:${name}`, { bubbles: true, cancelable: true, detail: { id: record.directUploadId, file: record.file, ...detail } }));
  }

  // Submitting while files are still uploading waits for them, then submits for real.
  // If one of them fails, the form stays put so the user can retry or remove it.
  onSubmit = (event) => {
    if (event.defaultPrevented || !this.records.some((record) => record.transfer)) return;

    event.preventDefault();
    this.pendingSubmit = { submitter: event.submitter };
    this.announce(this.t("waiting"));
  };

  resumeSubmit() {
    if (!this.pendingSubmit || this.records.some((record) => record.transfer)) return;

    const { submitter } = this.pendingSubmit;
    this.pendingSubmit = null;
    if (!this.form || this.records.some((record) => record.state === "error")) return;
    this.form.requestSubmit(submitter?.isConnected && submitter.form === this.form ? submitter : undefined);
  }

  succeed(record) {
    this.setProgress(record, 100);
    this.setState(record, "success");
    this.announce(this.t("uploaded", { name: record.file.name }));
  }

  fail(record, message) {
    this.setState(record, "error", message);
    this.announce(this.t("failed_named", { name: record.file.name, error: message }));
  }

  // ---------------------------------------------------------------------------
  // Helpers
  // ---------------------------------------------------------------------------

  // Points out markup that would silently not work. Only logs; nothing changes.
  checkSetup() {
    const warn = (message, ...context) => console.warn(`file-upload: ${message}`, ...context);

    if (!this.hasInputTarget) return warn('add data-file-upload-target="input" to the <input type="file">.', this.element);
    const input = this.inputTarget;
    if (input.type !== "file") warn('the input target must be an <input type="file">.', input);
    if (!input.name && !input.form) warn("the file input has no name and no form, so its files won't be submitted.", input);
    if (input.multiple && !input.name.endsWith("[]")) warn(`"${input.name}" is a multiple input, so Rails needs its name to end with [] to receive every file.`, input);
    if (this.maxFilesValue > 0 && !input.multiple) warn("maxFiles only applies to inputs with the multiple attribute.", input);
    if (this.hasTemplateTarget !== this.hasListTarget) warn("the template and list targets work together; add both or neither.", this.element);
    if (this.hasTemplateTarget) {
      const item = this.templateTarget.content?.firstElementChild;
      if (this.templateTarget.tagName !== "TEMPLATE") warn("the template target must be a <template> element.", this.templateTarget);
      else if (!item?.matches("[data-file-upload-target~='item']")) warn('the first element inside the <template> needs data-file-upload-target="item".', this.templateTarget);
    }
    if (this.hasStatusTarget && !this.statusTarget.hasAttribute("aria-live") && this.statusTarget.getAttribute("role") !== "status") {
      warn('the status target needs aria-live="polite" (or role="status") so screen readers announce changes.', this.statusTarget);
    }
    this.dropzoneTargets.forEach((dropzone) => {
      if (dropzone.tabIndex < 0 && !dropzone.matches("button") && (dropzone.dataset.action || "").includes("file-upload#open")) {
        warn('this dropzone opens the picker but can\'t be reached with the keyboard; add role="button" and tabindex="0".', dropzone);
      }
    });
  }

  get multiple() {
    return this.hasInputTarget && this.inputTarget.multiple;
  }

  // Picked files plus any server-rendered items that are still in the list.
  get count() {
    return this.hasListTarget ? this.itemTargets.length : this.records.length;
  }

  // True while Active Storage uploads the form's files; the list is locked until it finishes.
  get uploading() {
    return this.element.hasAttribute("data-uploading");
  }

  get autoUploading() {
    return this.autoUploadValue && this.hasInputTarget && Boolean(this.inputTarget.dataset.directUploadUrl);
  }

  // Records in the order their items appear in the list.
  get orderedRecords() {
    const before = (a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
    return [...this.records].sort((a, b) => (a.element && b.element && a.element !== b.element ? before(a.element, b.element) : 0));
  }

  get reducedMotion() {
    return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  }

  // Buttons (and button-like dropzones) that open the file picker.
  get openers() {
    const dropzones = this.dropzoneTargets.filter((dropzone) => dropzone.matches("button, [role='button']"));
    return [...new Set([...dropzones, ...this.element.querySelectorAll("[data-action*='file-upload#open']")])];
  }

  progressBars(element) {
    return element.querySelectorAll("[role='progressbar']");
  }

  recordFor(element) {
    return this.records.find((record) => record.element === element);
  }

  sameFile(a, b) {
    return a.name === b.name && a.size === b.size && a.lastModified === b.lastModified;
  }

  // Matches the item itself as well as anything inside it.
  fields(element, name) {
    const selector = `[data-file-upload-field~='${name}']`;
    return [...(element.matches(selector) ? [element] : []), ...element.querySelectorAll(selector)];
  }

  kindOf(file, extension) {
    const group = file.type.split("/")[0];
    if (["image", "video", "audio"].includes(group)) return group;
    return EXTENSION_KINDS[extension] || "file";
  }

  // Sizes use the page's locale for the number ("1,5 MB" on a French page).
  formatBytes(bytes) {
    const units = this.t("units").split(/\s+/);
    let value = bytes;
    let unit = 0;
    while (value >= 1024 && unit < units.length - 1) {
      value /= 1024;
      unit += 1;
    }
    const digits = unit === 0 || value >= 10 ? 0 : 1;
    return `${new Intl.NumberFormat(this.locale, { maximumFractionDigits: digits }).format(value)} ${units[unit]}`;
  }

  get locale() {
    return this.element.closest("[lang]")?.lang || undefined;
  }

  // Looks a message up in the element's overrides, then the app-wide table, and fills in %{…}.
  t(key, values = {}) {
    const template = this.messagesValue[key] ?? this.constructor.messages[key] ?? MESSAGES[key] ?? key;
    return template.replace(/%\{(\w+)\}/g, (match, name) => (name in values ? values[name] : match));
  }

  get countMessage() {
    return this.maxFilesValue === 1 ? this.t("count_one") : this.t("count", { max: this.maxFilesValue });
  }
}

Examples

Basic file input

The native file input, styled with Tailwind's file: variant. No JavaScript.

PDF or Word document, up to 5 MB.

<%# No JavaScript needed: this is the native input, styled with Tailwind's file: variant. %>
<div class="mx-auto w-full max-w-sm">
  <label for="resume" class="mb-1.5 block text-sm font-medium text-neutral-900 dark:text-neutral-100">Resume</label>
  <input
    id="resume"
    name="application[resume]"
    type="file"
    accept=".pdf,.doc,.docx"
    aria-describedby="resume_hint"
    class="block w-full cursor-pointer rounded-lg border border-black/10 bg-white text-sm text-neutral-600 shadow-xs transition-colors duration-150 ease-out file:mr-3 file:cursor-pointer file:border-0 file:border-r file:border-black/10 file:bg-neutral-50 file:px-3.5 file:py-2 file:text-sm file:font-medium file:text-neutral-800 file:transition-colors file:duration-150 hover:file:bg-neutral-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:border-white/10 dark:bg-neutral-800/60 dark:text-neutral-300 dark:file:border-white/10 dark:file:bg-neutral-700/60 dark:file:text-neutral-50 dark:hover:file:bg-neutral-700 dark:focus-visible:outline-neutral-200">
  <p id="resume_hint" class="mt-1.5 text-xs text-neutral-500 dark:text-neutral-400">PDF or Word document, up to 5 MB.</p>
</div>

Upload button

A button for a single file. The chosen file's name and size appear next to it, the button turns into Replace, and files over 10 MB are refused with an inline message.

No file chosen

<div
  class="group/upload mx-auto w-full max-w-sm"
  data-controller="file-upload"
  data-file-upload-max-size-value="<%= 10.megabytes %>">
  <label id="contract_label" for="contract" class="mb-1.5 block text-sm font-medium text-neutral-900 dark:text-neutral-100">Signed contract</label>

  <div class="flex min-h-9 items-center gap-3">
    <%# The real input. It stays in the form and always holds the selected file. %>
    <input id="contract" name="deal[contract]" type="file" accept=".pdf" class="sr-only" tabindex="-1" data-file-upload-target="input">

    <button
      type="button"
      id="contract_button"
      aria-labelledby="contract_label contract_button"
      data-action="file-upload#open"
      class="shrink-0 flex items-center justify-center gap-1.5 rounded-lg border border-neutral-400/30 bg-neutral-800 px-3.5 py-2 text-sm font-medium whitespace-nowrap text-white shadow-sm transition-all duration-100 ease-in-out select-none hover:bg-neutral-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-800 dark:hover:bg-neutral-100 dark:focus-visible:outline-neutral-200">
      <svg xmlns="http://www.w3.org/2000/svg" class="size-4" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" stroke="currentColor"><path d="M9 11.75V2.75"></path><path d="M5.75 6 9 2.75 12.25 6"></path><path d="M2.75 11.75v1.5a2 2 0 0 0 2 2h8.5a2 2 0 0 0 2-2v-1.5"></path></g></svg>
      <span class="group-data-has-files/upload:hidden">Choose PDF</span>
      <span class="hidden group-data-has-files/upload:inline">Replace</span>
    </button>

    <p class="truncate text-sm text-neutral-500 group-data-has-files/upload:hidden dark:text-neutral-400">No file chosen</p>

    <div data-file-upload-target="list" class="min-w-0 flex-1"></div>
    <template data-file-upload-target="template">
      <div data-file-upload-target="item" class="flex min-w-0 items-center gap-1">
        <span data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 truncate text-sm font-medium text-neutral-900 dark:text-neutral-100"></span>
        <span data-file-upload-field="size" class="shrink-0 text-sm text-neutral-500 tabular-nums dark:text-neutral-400"></span>
        <button
          type="button"
          data-action="file-upload#remove"
          data-file-upload-field="remove"
          class="relative flex size-6 shrink-0 items-center justify-center rounded-md bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none after:absolute after:-inset-2 hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
          <svg class="size-3.5" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
        </button>
      </div>
    </template>
  </div>

  <p data-file-upload-target="error" hidden class="mt-1.5 text-xs text-red-600 dark:text-red-400"></p>
  <p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
</div>

Drag and drop dropzone

Drop several files or press Enter or Space to browse. Each file gets a row with a type badge or image thumbnail, its size and a remove button. Drag a file over it to see the sheets fan out.

Drop files here or browse

Any file type, as many as you need.

    <div class="group/upload mx-auto w-full max-w-md" data-controller="file-upload">
      <input id="project_files" name="project[files][]" type="file" multiple class="sr-only" tabindex="-1" aria-label="Project files" data-file-upload-target="input">
    
      <%# Click, press Enter/Space, or drop files. data-drag="accept" is set while files hover over it. %>
      <div
        role="button"
        tabindex="0"
        aria-describedby="project_files_hint"
        data-file-upload-target="dropzone"
        data-action="click->file-upload#open keydown.enter->file-upload#open keydown.space->file-upload#open:prevent"
        class="group/dropzone flex cursor-pointer flex-col items-center justify-center rounded-xl border border-dashed border-neutral-300 bg-neutral-50/60 px-6 py-9 text-center transition-[background-color,border-color] duration-150 ease-out hover:border-neutral-400 hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 data-[drag=accept]:border-solid data-[drag=accept]:border-neutral-900 data-[drag=accept]:bg-neutral-100 motion-reduce:transition-none dark:border-white/15 dark:bg-white/[0.03] dark:hover:border-white/25 dark:hover:bg-white/5 dark:focus-visible:outline-neutral-200 dark:data-[drag=accept]:border-white dark:data-[drag=accept]:bg-white/10">
        <%# Three sheets of paper that fan out on hover and lift when files are dragged over. %>
        <div class="relative mb-4 flex h-12 w-20 items-end justify-center" aria-hidden="true">
          <span class="absolute bottom-0 h-10 w-8 origin-bottom -translate-x-2 -rotate-6 rounded-md border border-black/10 bg-white shadow-xs transition-transform duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-hover/dropzone:-translate-x-3 group-hover/dropzone:-rotate-12 group-data-[drag=accept]/dropzone:-translate-x-5 group-data-[drag=accept]/dropzone:-rotate-[18deg] motion-reduce:transition-none dark:border-white/10 dark:bg-neutral-700"></span>
          <span class="absolute bottom-0 h-10 w-8 origin-bottom translate-x-2 rotate-6 rounded-md border border-black/10 bg-white shadow-xs transition-transform duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-hover/dropzone:translate-x-3 group-hover/dropzone:rotate-12 group-data-[drag=accept]/dropzone:translate-x-5 group-data-[drag=accept]/dropzone:rotate-[18deg] motion-reduce:transition-none dark:border-white/10 dark:bg-neutral-700"></span>
          <span class="relative flex h-11 w-9 items-center justify-center rounded-md border border-black/10 bg-white text-neutral-700 shadow-sm transition-transform duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-data-[drag=accept]/dropzone:-translate-y-2 motion-reduce:transition-none dark:border-white/15 dark:bg-neutral-600 dark:text-neutral-100">
            <svg xmlns="http://www.w3.org/2000/svg" class="size-4" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" stroke="currentColor"><path d="M9 11.75V2.75"></path><path d="M5.75 6 9 2.75 12.25 6"></path><path d="M2.75 11.75v1.5a2 2 0 0 0 2 2h8.5a2 2 0 0 0 2-2v-1.5"></path></g></svg>
          </span>
        </div>
    
        <p class="text-sm font-medium text-neutral-900 group-data-[drag=accept]/dropzone:hidden dark:text-neutral-100">Drop files here or <span class="underline decoration-neutral-300 underline-offset-4 dark:decoration-neutral-600">browse</span></p>
        <p class="hidden text-sm font-medium text-neutral-900 group-data-[drag=accept]/dropzone:block dark:text-neutral-100">Let go to add them</p>
        <p id="project_files_hint" class="mt-1 text-xs text-neutral-500 dark:text-neutral-400">Any file type, as many as you need.</p>
      </div>
    
      <ul data-file-upload-target="list" aria-label="Selected files"></ul>
    
      <%# One of these is rendered per file. The spacing lives on the <li> so rows can animate in and out cleanly. %>
      <template data-file-upload-target="template">
        <li data-file-upload-target="item" class="group/file pt-2">
          <div class="flex items-center gap-3 rounded-xl border border-black/10 bg-white p-1.5 pr-2.5 shadow-xs dark:border-white/10 dark:bg-neutral-800/60">
            <div class="relative flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md bg-neutral-100 dark:bg-neutral-700/60">
              <span data-file-upload-field="extension" class="text-[10px] font-bold tracking-wide text-neutral-500 uppercase group-data-[kind=archive]/file:text-amber-600 group-data-[kind=pdf]/file:text-red-600 group-data-[kind=sheet]/file:text-emerald-600 group-data-[kind=video]/file:text-violet-600 dark:text-neutral-300 dark:group-data-[kind=archive]/file:text-amber-400 dark:group-data-[kind=pdf]/file:text-red-400 dark:group-data-[kind=sheet]/file:text-emerald-400 dark:group-data-[kind=video]/file:text-violet-400"></span>
              <img data-file-upload-field="preview" alt="" class="absolute inset-0 size-full object-cover">
            </div>
            <div class="min-w-0 flex-1">
              <p data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 truncate text-sm font-medium text-neutral-900 dark:text-neutral-100"></p>
              <p data-file-upload-field="size" class="text-xs text-neutral-500 tabular-nums dark:text-neutral-400"></p>
            </div>
            <button
              type="button"
              data-action="file-upload#remove"
              data-file-upload-field="remove"
              class="relative flex size-7 shrink-0 items-center justify-center rounded-md bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none after:absolute after:-inset-2 hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
              <svg class="size-3.5" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
            </button>
          </div>
        </li>
      </template>
    
      <p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
    </div>

    Validation

    A compact dropzone limited to three PDF, PNG or JPG files of 2 MB each. Files that don't qualify are refused with an inline message, unsupported files turn the dropzone red while you drag them, and it locks once the limit is reached.

    0 of 3

    Add receipts PDF, PNG or JPG. Up to 2 MB each.

      <%# Limits are enforced for picked, dropped and pasted files alike. Always validate again on the server. %>
      <div
        class="group/upload mx-auto w-full max-w-md"
        data-controller="file-upload"
        data-file-upload-max-files-value="3"
        data-file-upload-max-size-value="<%= 2.megabytes %>">
        <div class="mb-1.5 flex items-baseline justify-between">
          <label for="receipts" class="text-sm font-medium text-neutral-900 dark:text-neutral-100">Receipts</label>
          <p class="text-xs text-neutral-500 tabular-nums dark:text-neutral-400"><span data-file-upload-target="count">0</span> of 3</p>
        </div>
      
        <input id="receipts" name="expense[receipts][]" type="file" multiple accept="application/pdf,image/png,image/jpeg" class="sr-only" tabindex="-1" data-file-upload-target="input">
      
        <%# data-drag="reject" is set when the dragged files can't be accepted; data-full when the limit is reached. %>
        <div
          role="button"
          tabindex="0"
          aria-describedby="receipts_hint"
          data-file-upload-target="dropzone"
          data-action="click->file-upload#open keydown.enter->file-upload#open keydown.space->file-upload#open:prevent"
          class="group/dropzone flex cursor-pointer items-center gap-3 rounded-xl border border-dashed border-neutral-300 bg-neutral-50/60 p-3 transition-[background-color,border-color,opacity] duration-150 ease-out hover:border-neutral-400 hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 group-data-full/upload:cursor-not-allowed group-data-full/upload:opacity-60 data-[drag=accept]:border-solid data-[drag=accept]:border-neutral-900 data-[drag=accept]:bg-neutral-100 data-[drag=reject]:border-solid data-[drag=reject]:border-red-500 data-[drag=reject]:bg-red-50 motion-reduce:transition-none dark:border-white/15 dark:bg-white/[0.03] dark:hover:border-white/25 dark:hover:bg-white/5 dark:focus-visible:outline-neutral-200 dark:data-[drag=accept]:border-white dark:data-[drag=accept]:bg-white/10 dark:data-[drag=reject]:border-red-400 dark:data-[drag=reject]:bg-red-500/10">
          <span class="flex size-10 shrink-0 items-center justify-center rounded-lg border border-black/10 bg-white text-neutral-600 shadow-xs transition-[color,scale] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-data-[drag=accept]/dropzone:scale-110 group-data-[drag=reject]/dropzone:text-red-600 motion-reduce:transition-none dark:border-white/10 dark:bg-neutral-700 dark:text-neutral-200 dark:group-data-[drag=reject]/dropzone:text-red-400" aria-hidden="true">
            <svg xmlns="http://www.w3.org/2000/svg" class="size-[18px] group-data-[drag=reject]/dropzone:hidden" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" stroke="currentColor"><path d="M9 11.75V2.75"></path><path d="M5.75 6 9 2.75 12.25 6"></path><path d="M2.75 11.75v1.5a2 2 0 0 0 2 2h8.5a2 2 0 0 0 2-2v-1.5"></path></g></svg>
            <svg class="hidden size-[18px] group-data-[drag=reject]/dropzone:block" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><circle cx="9" cy="9" r="6.25" /><path d="m4.6 13.4 8.8-8.8" /></svg>
          </span>
          <span class="min-w-0 text-left">
            <span class="block text-sm font-medium text-neutral-900 group-data-full/upload:hidden group-data-[drag=reject]/dropzone:hidden dark:text-neutral-100">Add receipts</span>
            <span class="hidden text-sm font-medium text-neutral-900 group-data-full/upload:block group-data-[drag=reject]/dropzone:hidden dark:text-neutral-100">That’s all three</span>
            <span class="hidden text-sm font-medium text-red-700 group-data-[drag=reject]/dropzone:block dark:text-red-400">Can’t add this here</span>
            <span id="receipts_hint" class="block text-xs text-neutral-500 dark:text-neutral-400">PDF, PNG or JPG. Up to 2 MB each.</span>
          </span>
        </div>
      
        <p data-file-upload-target="error" hidden class="mt-2 text-xs text-red-600 dark:text-red-400"></p>
      
        <ul data-file-upload-target="list" aria-label="Selected receipts"></ul>
      
        <template data-file-upload-target="template">
          <li data-file-upload-target="item" class="pt-2">
            <div class="flex items-center gap-2.5 rounded-lg bg-neutral-100/80 py-1.5 pr-1.5 pl-2.5 dark:bg-white/5">
              <svg class="size-4 shrink-0 text-neutral-500 dark:text-neutral-400" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.25 1.75h-4.5a2 2 0 0 0-2 2v10.5a2 2 0 0 0 2 2h6.5a2 2 0 0 0 2-2v-8.5l-4-4Z" /><path d="M10.25 1.75v3a1 1 0 0 0 1 1h3" /></svg>
              <p data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 flex-1 truncate text-sm text-neutral-900 dark:text-neutral-100"></p>
              <p data-file-upload-field="size" class="shrink-0 text-xs text-neutral-500 tabular-nums dark:text-neutral-400"></p>
              <button
                type="button"
                data-action="file-upload#remove"
                data-file-upload-field="remove"
                class="relative flex size-6 shrink-0 items-center justify-center rounded-md bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none after:absolute after:-inset-2 hover:bg-neutral-200 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
                <svg class="size-3.5" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
              </button>
            </div>
          </li>
        </template>
      
        <p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
      </div>

      Image grid

      A photo gallery uploader with instant thumbnails. The first tile adds photos and accepts drops; photos that are already attached sit in the same grid and can be removed the same way.

      2 of 8

      • Add
      • watch-front.jpg
      • watch-detail.jpg

      JPG, PNG or WebP. Up to 8 MB each.

      <div
        class="group/upload mx-auto w-full max-w-md"
        data-controller="file-upload"
        data-file-upload-max-files-value="8"
        data-file-upload-max-size-value="<%= 8.megabytes %>">
        <div class="mb-2 flex items-baseline justify-between">
          <label for="listing_photos" class="text-sm font-medium text-neutral-900 dark:text-neutral-100">Listing photos</label>
          <p class="text-xs text-neutral-500 tabular-nums dark:text-neutral-400"><span data-file-upload-target="count">2</span> of 8</p>
        </div>
      
        <%# Like form.file_field with multiple: true, an empty value first: removing every photo then detaches them all. %>
        <input type="hidden" name="listing[photos][]" value="" autocomplete="off">
        <input id="listing_photos" name="listing[photos][]" type="file" multiple accept="image/*" class="sr-only" tabindex="-1" data-file-upload-target="input">
      
        <ul data-file-upload-target="list" class="grid grid-cols-3 gap-2 sm:grid-cols-4" aria-label="Photos">
          <%# The "add" tile is also the dropzone. It disappears once the limit is reached. %>
          <li class="group-data-full/upload:hidden">
            <div
              role="button"
              tabindex="0"
              aria-label="Add photos"
              data-file-upload-target="dropzone"
              data-action="click->file-upload#open keydown.enter->file-upload#open keydown.space->file-upload#open:prevent"
              class="group/dropzone flex aspect-square cursor-pointer flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-neutral-300 bg-neutral-50/60 text-neutral-500 transition-[background-color,border-color,color] duration-150 ease-out hover:border-neutral-400 hover:bg-neutral-50 hover:text-neutral-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 data-[drag=accept]:border-solid data-[drag=accept]:border-neutral-900 data-[drag=accept]:bg-neutral-100 data-[drag=accept]:text-neutral-900 data-[drag=reject]:border-red-500 data-[drag=reject]:text-red-600 motion-reduce:transition-none dark:border-white/15 dark:bg-white/[0.03] dark:text-neutral-400 dark:hover:border-white/25 dark:hover:bg-white/5 dark:hover:text-neutral-100 dark:focus-visible:outline-neutral-200 dark:data-[drag=accept]:border-white dark:data-[drag=accept]:bg-white/10 dark:data-[drag=accept]:text-white dark:data-[drag=reject]:border-red-400 dark:data-[drag=reject]:text-red-400">
              <svg xmlns="http://www.w3.org/2000/svg" class="size-5 transition-transform duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-data-[drag=accept]/dropzone:scale-125 motion-reduce:transition-none" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="currentColor"><path d="M14.75,9.75H3.25c-.414,0-.75-.336-.75-.75s.336-.75,.75-.75H14.75c.414,0,.75,.336,.75,.75s-.336,.75-.75,.75Z"></path><path d="M9,15.5c-.414,0-.75-.336-.75-.75V3.25c0-.414,.336-.75,.75-.75s.75,.336,.75,.75V14.75c0,.414-.336,.75-.75,.75Z"></path></g></svg>
              <span class="text-xs font-medium">Add</span>
            </div>
          </li>
      
          <%#
            Photos that are already attached are rendered by the server, each with a hidden field holding its
            signed_id (value: photo.signed_id). Submitting replaces the whole set, so these fields keep the
            photos that stay, and removing a tile removes its field, which detaches that photo.
          %>
          <li data-file-upload-target="item" class="group/file relative aspect-square overflow-hidden rounded-xl bg-neutral-100 after:pointer-events-none after:absolute after:inset-0 after:rounded-xl after:shadow-[inset_0_0_0_1px_rgb(0_0_0_/_10%)] dark:bg-neutral-800 dark:after:shadow-[inset_0_0_0_1px_rgb(255_255_255_/_10%)]">
            <img src="https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=320&h=320&fit=crop&auto=format&q=80" alt="" class="size-full object-cover">
            <span data-file-upload-field="name" class="sr-only">watch-front.jpg</span>
            <input type="hidden" name="listing[photos][]" value="watch-front-signed-id" autocomplete="off">
            <button type="button" data-action="file-upload#remove" aria-label="Remove watch-front.jpg" class="absolute top-1.5 right-1.5 flex size-6 items-center justify-center rounded-full bg-neutral-900/70 text-white opacity-0 backdrop-blur-sm transition-[opacity,background-color] duration-150 ease-out group-hover/file:opacity-100 after:absolute after:-inset-2 hover:bg-neutral-900 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-white pointer-coarse:opacity-100">
              <svg class="size-3" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
            </button>
          </li>
          <li data-file-upload-target="item" class="group/file relative aspect-square overflow-hidden rounded-xl bg-neutral-100 after:pointer-events-none after:absolute after:inset-0 after:rounded-xl after:shadow-[inset_0_0_0_1px_rgb(0_0_0_/_10%)] dark:bg-neutral-800 dark:after:shadow-[inset_0_0_0_1px_rgb(255_255_255_/_10%)]">
            <img src="https://images.unsplash.com/photo-1524805444758-089113d48a6d?w=320&h=320&fit=crop&auto=format&q=80" alt="" class="size-full object-cover">
            <span data-file-upload-field="name" class="sr-only">watch-detail.jpg</span>
            <input type="hidden" name="listing[photos][]" value="watch-detail-signed-id" autocomplete="off">
            <button type="button" data-action="file-upload#remove" aria-label="Remove watch-detail.jpg" class="absolute top-1.5 right-1.5 flex size-6 items-center justify-center rounded-full bg-neutral-900/70 text-white opacity-0 backdrop-blur-sm transition-[opacity,background-color] duration-150 ease-out group-hover/file:opacity-100 after:absolute after:-inset-2 hover:bg-neutral-900 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-white pointer-coarse:opacity-100">
              <svg class="size-3" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
            </button>
          </li>
        </ul>
      
        <template data-file-upload-target="template">
          <li data-file-upload-target="item" class="group/file relative aspect-square overflow-hidden rounded-xl bg-neutral-100 after:pointer-events-none after:absolute after:inset-0 after:rounded-xl after:shadow-[inset_0_0_0_1px_rgb(0_0_0_/_10%)] dark:bg-neutral-800 dark:after:shadow-[inset_0_0_0_1px_rgb(255_255_255_/_10%)]">
            <img data-file-upload-field="preview" alt="" class="size-full object-cover">
            <span data-file-upload-field="name" class="sr-only"></span>
            <button type="button" data-action="file-upload#remove" data-file-upload-field="remove" class="absolute top-1.5 right-1.5 flex size-6 items-center justify-center rounded-full bg-neutral-900/70 text-white opacity-0 backdrop-blur-sm transition-[opacity,background-color] duration-150 ease-out group-hover/file:opacity-100 after:absolute after:-inset-2 hover:bg-neutral-900 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-white pointer-coarse:opacity-100">
              <svg class="size-3" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
            </button>
          </li>
        </template>
      
        <p class="mt-2 text-xs text-neutral-500 dark:text-neutral-400">JPG, PNG or WebP. Up to 8 MB each.</p>
        <p data-file-upload-target="error" hidden class="mt-1 text-xs text-red-600 dark:text-red-400"></p>
        <p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
      </div>

      Avatar upload

      A profile photo uploader with a circular preview. Click the photo or drop a new one on it to replace it, or remove it to fall back to the placeholder.

      Profile photo

      PNG, JPG, GIF or WebP. 2 MB max.

      <div
        class="group/upload mx-auto flex w-full max-w-sm items-center gap-4"
        data-controller="file-upload"
        data-file-upload-max-size-value="<%= 2.megabytes %>">
        <%#
          Fields named user[avatar] submit in order and the last one wins: this empty value (removes the photo),
          then a newly picked file, then the current photo's signed_id inside the list (keeps it). Picking or
          removing a photo removes the signed_id field with the old photo, so the right value comes last.
        %>
        <input type="hidden" name="user[avatar]" value="" autocomplete="off">
        <input id="user_avatar" name="user[avatar]" type="file" accept="image/png,image/jpeg,image/gif,image/webp" class="sr-only" tabindex="-1" aria-label="Profile photo" data-file-upload-target="input">
      
        <%# The circle is a dropzone too: click it or drop a photo on it. %>
        <button
          type="button"
          aria-label="Change profile photo"
          data-file-upload-target="dropzone"
          data-action="file-upload#open"
          class="group/dropzone relative size-20 shrink-0 cursor-pointer rounded-full bg-neutral-100 text-neutral-400 outline-offset-2 transition-[scale,outline-color] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-full after:shadow-[inset_0_0_0_1px_rgb(0_0_0_/_10%)] focus-visible:outline-2 focus-visible:outline-neutral-600 data-[drag=accept]:scale-105 data-[drag=accept]:outline-2 data-[drag=accept]:outline-neutral-900 data-[drag=reject]:outline-2 data-[drag=reject]:outline-red-500 motion-reduce:transition-none dark:bg-neutral-800 dark:text-neutral-500 dark:after:shadow-[inset_0_0_0_1px_rgb(255_255_255_/_10%)] dark:focus-visible:outline-neutral-200 dark:data-[drag=accept]:outline-white">
          <%# Placeholder, visible when there is no photo %>
          <svg class="absolute inset-0 m-auto size-8" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="9" cy="6" r="2.75" /><path d="M3.5 15.25c.6-2.6 2.8-4 5.5-4s4.9 1.4 5.5 4" /></svg>
      
          <%# The list holds one item: the current photo. A new pick cross-fades over it. %>
          <span data-file-upload-target="list" class="pointer-events-none absolute inset-0 block overflow-hidden rounded-full">
            <%# The current photo, rendered by the server. In your app: value: current_user.avatar.signed_id %>
            <span data-file-upload-target="item" class="absolute inset-0">
              <img src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=160&h=160&fit=crop&crop=face&auto=format&q=80" alt="" class="absolute inset-0 size-full object-cover">
              <input type="hidden" name="user[avatar]" value="current-avatar-signed-id" autocomplete="off">
            </span>
          </span>
      
          <span class="absolute inset-0 z-[5] flex items-center justify-center rounded-full bg-neutral-900/50 text-white opacity-0 transition-opacity duration-150 ease-out group-hover/dropzone:opacity-100 group-focus-visible/dropzone:opacity-100 group-data-[drag=accept]/dropzone:opacity-100 motion-reduce:transition-none" aria-hidden="true">
            <svg class="size-5" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6.6 4.25 7.4 3a1 1 0 0 1 .85-.5h1.5a1 1 0 0 1 .85.5l.8 1.25h1.85a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H4.75a2 2 0 0 1-2-2v-6.5a2 2 0 0 1 2-2H6.6Z" /><circle cx="9" cy="9.5" r="2.5" /></svg>
          </span>
        </button>
      
        <template data-file-upload-target="template">
          <img data-file-upload-target="item" data-file-upload-field="preview" alt="" class="absolute inset-0 size-full object-cover">
        </template>
      
        <div class="min-w-0">
          <p class="text-sm font-medium text-neutral-900 dark:text-neutral-100">Profile photo</p>
          <p class="mt-0.5 text-xs text-neutral-500 dark:text-neutral-400">PNG, JPG, GIF or WebP. 2 MB max.</p>
          <div class="mt-2.5 flex items-center gap-2">
            <button
              type="button"
              data-action="file-upload#open"
              class="flex items-center justify-center gap-1.5 rounded-lg border border-neutral-400/30 bg-neutral-800 px-2.5 py-1.5 text-xs font-medium whitespace-nowrap text-white shadow-sm transition-all duration-100 ease-in-out select-none hover:bg-neutral-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-800 dark:hover:bg-neutral-100 dark:focus-visible:outline-neutral-200">
              <span class="group-data-has-files/upload:hidden">Upload photo</span>
              <span class="hidden group-data-has-files/upload:inline">Change</span>
            </button>
            <button
              type="button"
              data-action="file-upload#clear"
              class="hidden items-center justify-center gap-1.5 rounded-lg bg-transparent px-2.5 py-1.5 text-xs font-medium whitespace-nowrap text-neutral-800 transition-all duration-100 ease-in-out select-none group-data-has-files/upload:flex hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-50 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
              Remove
            </button>
          </div>
          <p data-file-upload-target="error" hidden class="mt-2 text-xs text-red-600 dark:text-red-400"></p>
        </div>
      
        <p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
      </div>

      Upload progress

      Per-file progress with success and error states. Uploads on this page are simulated, and every third file fails once so you can try Retry. In your app the same markup follows Active Storage's direct upload events.

      Launch assets

      Drop files anywhere on this card.

      No files yet.

      • pdf

        press-kit.pdf

        2.4 MB · Uploaded

      <%#
        Progress, success and error states for each file.
      
        Add `direct_upload: true` to the file field: the controller shows the real progress from Active
        Storage's direct-upload events, and Retry resubmits the form.
      %>
      <div
        class="group/upload mx-auto w-full max-w-md overflow-hidden rounded-xl border border-black/10 bg-white shadow-xs transition-[border-color,box-shadow] duration-150 ease-out data-[drag=accept]:border-neutral-900 data-[drag=accept]:shadow-md motion-reduce:transition-none dark:border-white/10 dark:bg-neutral-900 dark:data-[drag=accept]:border-white"
        data-controller="file-upload"
        data-file-upload-target="dropzone"
        data-file-upload-max-size-value="<%= 50.megabytes %>">
        <div class="flex items-center justify-between gap-3 px-4 py-3">
          <div class="min-w-0">
            <p class="text-sm font-semibold text-neutral-900 dark:text-white">Launch assets</p>
            <p class="text-xs text-neutral-500 dark:text-neutral-400">Drop files anywhere on this card.</p>
          </div>
          <%# Like form.file_field with multiple: true, an empty value first: removing every file then detaches them all. %>
          <input type="hidden" name="launch[assets][]" value="" autocomplete="off">
          <input id="launch_assets" name="launch[assets][]" type="file" multiple class="sr-only" tabindex="-1" aria-label="Launch assets" data-file-upload-target="input">
          <button
            type="button"
            data-action="file-upload#open"
            class="shrink-0 flex items-center justify-center gap-1.5 rounded-lg border border-neutral-400/30 bg-neutral-800 px-3 py-1.5 text-sm font-medium whitespace-nowrap text-white shadow-sm transition-all duration-100 ease-in-out select-none hover:bg-neutral-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-800 dark:hover:bg-neutral-100 dark:focus-visible:outline-neutral-200">
            <svg xmlns="http://www.w3.org/2000/svg" class="size-3.5" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="currentColor"><path d="M14.75,9.75H3.25c-.414,0-.75-.336-.75-.75s.336-.75,.75-.75H14.75c.414,0,.75,.336,.75,.75s-.336,.75-.75,.75Z"></path><path d="M9,15.5c-.414,0-.75-.336-.75-.75V3.25c0-.414,.336-.75,.75-.75s.75,.336,.75,.75V14.75c0,.414-.336,.75-.75,.75Z"></path></g></svg>
            Add files
          </button>
        </div>
      
        <p class="border-t border-black/5 px-4 py-8 text-center text-sm text-neutral-500 group-data-has-files/upload:hidden dark:border-white/5 dark:text-neutral-400">No files yet.</p>
      
        <ul data-file-upload-target="list" aria-label="Files">
          <%# A file that was uploaded earlier, rendered by the server. Its hidden signed_id (value: asset.signed_id) keeps it attached; removing the row detaches it. %>
          <li data-file-upload-target="item" data-state="success" data-kind="pdf" class="group/file relative flex items-center gap-3 border-t border-black/5 px-4 py-3 dark:border-white/5">
            <div class="relative flex size-9 shrink-0 items-center justify-center rounded-lg bg-neutral-100 dark:bg-neutral-800">
              <span class="text-[9px] font-bold tracking-wide text-red-600 uppercase dark:text-red-400">pdf</span>
              <span class="absolute -right-1 -bottom-1 flex size-4 items-center justify-center rounded-full bg-emerald-500 text-white ring-2 ring-white dark:ring-neutral-900" aria-hidden="true">
                <svg xmlns="http://www.w3.org/2000/svg" class="size-3" viewBox="0 0 18 18" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.5 9.5l3.5 3.5 7.5-8"></path></svg>
              </span>
            </div>
            <div class="min-w-0 flex-1">
              <p data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">press-kit.pdf</p>
              <p class="text-xs text-neutral-500 tabular-nums dark:text-neutral-400">2.4 MB · Uploaded</p>
              <input type="hidden" name="launch[assets][]" value="press-kit-signed-id" autocomplete="off">
            </div>
            <button type="button" data-action="file-upload#remove" aria-label="Remove press-kit.pdf" class="relative flex size-7 shrink-0 items-center justify-center rounded-md bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none after:absolute after:-inset-2 hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
              <svg class="size-3.5" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
            </button>
          </li>
        </ul>
      
        <%# data-state on the item ("queued", "uploading", "success" or "error") drives everything below through group-data-* classes. %>
        <template data-file-upload-target="template">
          <li data-file-upload-target="item" class="group/file relative flex items-center gap-3 border-t border-black/5 px-4 py-3 dark:border-white/5">
            <div class="relative flex size-9 shrink-0 items-center justify-center rounded-lg bg-neutral-100 dark:bg-neutral-800">
              <span data-file-upload-field="extension" class="text-[9px] font-bold tracking-wide text-neutral-500 uppercase group-data-[kind=archive]/file:text-amber-600 group-data-[kind=pdf]/file:text-red-600 group-data-[kind=sheet]/file:text-emerald-600 group-data-[kind=video]/file:text-violet-600 dark:text-neutral-300 dark:group-data-[kind=archive]/file:text-amber-400 dark:group-data-[kind=pdf]/file:text-red-400 dark:group-data-[kind=sheet]/file:text-emerald-400 dark:group-data-[kind=video]/file:text-violet-400"></span>
              <img data-file-upload-field="preview" alt="" class="absolute inset-0 size-full rounded-lg object-cover">
              <%# Success check: pops in when the upload finishes %>
              <span class="absolute -right-1 -bottom-1 flex size-4 scale-50 items-center justify-center rounded-full bg-emerald-500 text-white opacity-0 blur-[3px] ring-2 ring-white transition-[opacity,scale,filter] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] group-data-[state=success]/file:scale-100 group-data-[state=success]/file:opacity-100 group-data-[state=success]/file:blur-none motion-reduce:transition-none dark:ring-neutral-900" aria-hidden="true">
                <svg xmlns="http://www.w3.org/2000/svg" class="size-3" viewBox="0 0 18 18" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.5 9.5l3.5 3.5 7.5-8"></path></svg>
              </span>
              <%# Error mark %>
              <span class="absolute -right-1 -bottom-1 hidden size-4 items-center justify-center rounded-full bg-red-500 text-[10px] leading-none font-bold text-white ring-2 ring-white group-data-[state=error]/file:flex dark:ring-neutral-900" aria-hidden="true">!</span>
            </div>
      
            <div class="min-w-0 flex-1">
              <p data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 truncate text-sm font-medium text-neutral-900 dark:text-neutral-100"></p>
              <p class="text-xs text-neutral-500 tabular-nums group-data-[state=error]/file:hidden dark:text-neutral-400">
                <span data-file-upload-field="size"></span>
                <span class="hidden group-data-[state=queued]/file:inline">· Waiting…</span>
                <span class="hidden group-data-[state=uploading]/file:inline">· <span data-file-upload-field="percent">0%</span></span>
                <span class="hidden group-data-[state=success]/file:inline">· Uploaded</span>
              </p>
              <p data-file-upload-field="error" class="hidden truncate text-xs text-red-600 group-data-[state=error]/file:block dark:text-red-400"></p>
            </div>
      
            <button
              type="button"
              data-action="file-upload#retry"
              data-file-upload-field="retry"
              class="hidden shrink-0 items-center justify-center gap-1.5 rounded-md bg-transparent px-2 py-1 text-xs font-medium whitespace-nowrap text-neutral-800 transition-all duration-100 ease-in-out select-none group-data-[state=error]/file:flex hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-50 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
              Retry
            </button>
            <button
              type="button"
              data-action="file-upload#remove"
              data-file-upload-field="remove"
              class="relative flex size-7 shrink-0 items-center justify-center rounded-md bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none after:absolute after:-inset-2 hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
              <svg class="size-3.5" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
            </button>
      
            <%# A hairline progress bar along the bottom of the row, so nothing shifts when it comes and goes %>
            <div role="progressbar" aria-label="Upload progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" class="absolute inset-x-0 bottom-0 h-0.5 opacity-0 transition-opacity duration-300 ease-out group-data-[state=error]/file:opacity-100 group-data-[state=uploading]/file:opacity-100 motion-reduce:transition-none">
              <div data-file-upload-field="bar" class="h-full w-0 rounded-r-full bg-neutral-900 transition-[width] duration-200 ease-linear group-data-[state=error]/file:bg-red-500 motion-reduce:transition-none dark:bg-white"></div>
            </div>
          </li>
        </template>
      
        <p data-file-upload-target="error" hidden class="border-t border-black/5 px-4 py-2.5 text-xs text-red-600 dark:border-white/5 dark:text-red-400"></p>
        <p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
      </div>

      Chat attachments

      Compact attachment chips for a chat composer or comment box. Attach with the paperclip, drop files anywhere on the composer, or paste a screenshot into the text area. Upload progress is simulated.

      • pdf Q3-roadmap.pdf

      <%#
        Compact attachment chips for a chat composer or comment box. Attach with the paperclip, drop files on
        the composer, or paste an image straight into the textarea. With `direct_upload: true` on the file
        field, each chip shows Active Storage's upload progress.
      %>
      <div
        class="group/upload mx-auto w-full max-w-lg"
        data-controller="file-upload"
        data-file-upload-max-files-value="6"
        data-file-upload-max-size-value="<%= 10.megabytes %>">
        <div
          data-file-upload-target="dropzone"
          class="group/dropzone relative rounded-2xl border border-black/10 bg-white shadow-xs transition-[border-color,box-shadow] duration-150 ease-out focus-within:border-neutral-400 data-[drag=accept]:border-neutral-900 motion-reduce:transition-none dark:border-white/10 dark:bg-neutral-800/60 dark:focus-within:border-white/30 dark:data-[drag=accept]:border-white">
          <ul data-file-upload-target="list" class="flex flex-wrap gap-x-1.5 px-3" aria-label="Attachments">
            <%# An attachment that is already uploaded. Its hidden signed_id (value: attachment.signed_id) keeps it attached; removing the chip detaches it. %>
            <li data-file-upload-target="item" data-state="success" class="group/file mt-3 flex max-w-52 items-center gap-1.5 rounded-lg border border-black/10 bg-neutral-50 p-1 dark:border-white/10 dark:bg-white/5">
              <span class="flex size-6 shrink-0 items-center justify-center rounded-sm bg-white text-[8px] font-bold text-red-600 uppercase shadow-xs dark:bg-neutral-700 dark:text-red-400">pdf</span>
              <span data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 truncate text-xs font-medium text-neutral-800 dark:text-neutral-100">Q3-roadmap.pdf</span>
              <input type="hidden" name="reply[attachments][]" value="q3-roadmap-signed-id" autocomplete="off">
              <button type="button" data-action="file-upload#remove" aria-label="Remove Q3-roadmap.pdf" class="relative flex size-5 shrink-0 items-center justify-center rounded-md bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none after:absolute after:-inset-2 hover:bg-neutral-200 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
                <svg class="size-3" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
              </button>
            </li>
          </ul>
      
          <template data-file-upload-target="template">
            <li data-file-upload-target="item" class="group/file mt-3 flex max-w-52 items-center gap-1.5 rounded-lg border border-black/10 bg-neutral-50 p-1 transition-colors duration-150 data-[state=error]:border-red-300 data-[state=error]:bg-red-50 dark:border-white/10 dark:bg-white/5 dark:data-[state=error]:border-red-400/40 dark:data-[state=error]:bg-red-500/10">
              <span class="relative flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-sm bg-white shadow-xs dark:bg-neutral-700">
                <span data-file-upload-field="extension" class="text-[8px] font-bold text-neutral-500 uppercase dark:text-neutral-300"></span>
                <img data-file-upload-field="preview" alt="" class="absolute inset-0 size-full object-cover">
                <%# Progress ring, shown over the thumbnail while uploading %>
                <span class="absolute inset-0 flex items-center justify-center bg-white/80 opacity-0 transition-opacity duration-200 ease-out group-data-[state=uploading]/file:opacity-100 motion-reduce:transition-none dark:bg-neutral-800/80" aria-hidden="true">
                  <svg class="size-4 -rotate-90" viewBox="0 0 16 16" fill="none" stroke-width="2">
                    <circle cx="8" cy="8" r="6" class="stroke-neutral-200 dark:stroke-neutral-600" />
                    <circle data-file-upload-field="ring" cx="8" cy="8" r="6" pathLength="100" stroke-dasharray="100" stroke-dashoffset="100" stroke-linecap="round" class="stroke-neutral-900 transition-[stroke-dashoffset] duration-200 ease-linear motion-reduce:transition-none dark:stroke-white" />
                  </svg>
                </span>
              </span>
              <span data-file-upload-field="name" data-truncate="middle" class="flex min-w-0 truncate text-xs font-medium text-neutral-800 group-data-[state=error]/file:text-red-700 dark:text-neutral-100 dark:group-data-[state=error]/file:text-red-300"></span>
              <button type="button" data-action="file-upload#retry" data-file-upload-field="retry" aria-label="Retry upload" class="hidden size-5 shrink-0 items-center justify-center rounded-md bg-transparent text-red-600 transition-all duration-100 ease-in-out select-none group-data-[state=error]/file:flex hover:bg-red-100 hover:text-red-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-red-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-red-300 dark:hover:bg-red-500/20 dark:hover:text-red-200 dark:focus-visible:outline-red-400">
                <svg xmlns="http://www.w3.org/2000/svg" class="size-3.5" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="currentColor"><path d="M9.03,12.22c-.293-.293-.768-.293-1.061,0s-.293,.768,0,1.061l1.208,1.208c-.059,.002-.118,.012-.178,.012-3.032,0-5.5-2.467-5.5-5.5,0-1.616,.706-3.143,1.938-4.191,.315-.269,.354-.742,.085-1.057s-.74-.353-1.058-.085c-1.567,1.333-2.466,3.277-2.466,5.333,0,3.76,2.983,6.829,6.704,6.985l-.735,.735c-.293,.293-.293,.768,0,1.061,.146,.146,.338,.22,.53,.22s.384-.073,.53-.22l2.25-2.25c.293-.293,.293-.768,0-1.061l-2.25-2.25Z"></path><path d="M9.296,2.015l.735-.735c.293-.293,.293-.768,0-1.061s-.768-.293-1.061,0l-2.25,2.25c-.293,.293-.293,.768,0,1.061l2.25,2.25c.146,.146,.338,.22,.53,.22s.384-.073,.53-.22c.293-.293,.293-.768,0-1.061l-1.208-1.208c.059-.002,.118-.012,.177-.012,3.032,0,5.5,2.467,5.5,5.5,0,1.616-.706,3.143-1.938,4.191-.315,.269-.354,.742-.085,1.057,.148,.174,.359,.264,.571,.264,.172,0,.345-.059,.486-.179,1.567-1.333,2.466-3.277,2.466-5.333,0-3.76-2.983-6.829-6.704-6.985Z"></path></g></svg>
              </button>
              <button type="button" data-action="file-upload#remove" data-file-upload-field="remove" class="relative flex size-5 shrink-0 items-center justify-center rounded-md bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none after:absolute after:-inset-2 hover:bg-neutral-200 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
                <svg class="size-3" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></svg>
              </button>
            </li>
          </template>
      
          <label for="reply_body" class="sr-only">Reply</label>
          <textarea
            id="reply_body"
            name="reply[body]"
            rows="2"
            placeholder="Reply to Maya…"
            data-action="paste->file-upload#paste"
            class="block w-full resize-none border-0 bg-transparent px-4 pt-3 pb-1 text-sm text-neutral-900 placeholder:text-neutral-400 focus:ring-0 focus:outline-none dark:text-neutral-100 dark:placeholder:text-neutral-500"></textarea>
      
          <div class="flex items-center justify-between gap-2 p-2">
            <div class="flex items-center gap-2">
              <%# Like form.file_field with multiple: true, an empty value first: removing every file then detaches them all. %>
              <input type="hidden" name="reply[attachments][]" value="" autocomplete="off">
              <input id="reply_attachments" name="reply[attachments][]" type="file" multiple class="sr-only" tabindex="-1" aria-label="Attachments" data-file-upload-target="input">
              <button
                type="button"
                aria-label="Attach files"
                data-action="file-upload#open"
                class="flex size-8 items-center justify-center rounded-lg bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 group-data-full/upload:pointer-events-none group-data-full/upload:opacity-40 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200">
                <svg xmlns="http://www.w3.org/2000/svg" class="size-[18px]" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" stroke="currentColor"><path d="M10.985,5.422l-4.773,4.773c-.586,.586-.586,1.536,0,2.121h0c.586,.586,1.536,.586,2.121,0l4.95-4.95c1.172-1.172,1.172-3.071,0-4.243h0c-1.172-1.172-3.071-1.172-4.243,0l-4.95,4.95c-1.757,1.757-1.757,4.607,0,6.364h0c1.757,1.757,4.607,1.757,6.364,0l4.773-4.773"></path></g></svg>
              </button>
              <p class="hidden text-xs text-neutral-400 sm:block dark:text-neutral-500">Paste, drop or attach up to 6 files</p>
            </div>
            <button
              type="button"
              aria-label="Send reply"
              class="flex items-center justify-center gap-1.5 rounded-lg border border-neutral-400/30 bg-neutral-800 size-8 p-0 text-sm font-medium whitespace-nowrap text-white shadow-sm transition-all duration-100 ease-in-out select-none hover:bg-neutral-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-800 dark:hover:bg-neutral-100 dark:focus-visible:outline-neutral-200">
              <svg xmlns="http://www.w3.org/2000/svg" class="size-4" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" stroke="currentColor"><path d="M9 11.75V2.75"></path><path d="M5.75 6 9 2.75 12.25 6"></path><path d="M2.75 11.75v1.5a2 2 0 0 0 2 2h8.5a2 2 0 0 0 2-2v-1.5"></path></g></svg>
            </button>
          </div>
      
          <%# Shown while files are dragged over the composer %>
          <div class="pointer-events-none absolute inset-0 flex items-center justify-center rounded-2xl bg-white/85 text-sm font-medium text-neutral-900 opacity-0 backdrop-blur-[2px] transition-opacity duration-150 ease-out group-data-[drag=accept]/dropzone:opacity-100 motion-reduce:transition-none dark:bg-neutral-900/85 dark:text-white" aria-hidden="true">
            Drop to attach
          </div>
        </div>
      
        <p data-file-upload-target="error" hidden class="mt-2 text-xs text-red-600 dark:text-red-400"></p>
        <p data-file-upload-target="status" class="sr-only" aria-live="polite"></p>
      </div>

      ViewComponent

      Prefer Ruby? FileUpload::Component renders a dropzone, an upload button, an image grid or an avatar uploader from one call. Pass attachments: to show files that are already attached, error: for server-side validation messages, and direct_upload: true for Active Storage progress. The same options work with the shared partial; both are behind the buttons at the top of the page.

      0 of 3

      Drop files here or browse

      PDF, PNG or JPG. Up to 2 MB each.

      Profile photo

      PNG, JPG, GIF or WebP. 2 MB max.

      <%# FileUpload::Component writes the input, dropzone, templates, ARIA and Stimulus wiring for you. %>
      <div class="flex flex-col gap-8">
        <%= render FileUpload::Component.new(
          name: "expense[receipts]",
          label: "Receipts",
          hint: "PDF, PNG or JPG. Up to 2 MB each.",
          accept: "application/pdf,image/png,image/jpeg",
          max_files: 3,
          max_size: 2.megabytes
        ) %>
      
        <%= render FileUpload::Component.new(
          variant: :avatar,
          name: "user[avatar]",
          label: "Profile photo",
          hint: "PNG, JPG, GIF or WebP. 2 MB max.",
          max_size: 2.megabytes
        ) %>
      </div>

      Usage with Rails forms

      Mark your file_field as the input target. The controller keeps its file list in sync when files are dropped, pasted or removed, so the form submits as usual. Add direct_upload: true and each file shows real progress while Active Storage uploads it on submit.

      <%= form_with model: @project do |form| %>
        <div data-controller="file-upload" data-file-upload-max-size-value="<%= 25.megabytes %>">
          <%= form.file_field :documents,
                multiple: true,
                direct_upload: true,
                class: "sr-only",
                tabindex: -1,
                data: { file_upload_target: "input" } %>
      
          <%# dropzone, list and template from any example above %>
        </div>
      
        <%= form.submit "Save project" %>
      <% end %>
      

      Client-side limits are a convenience. Validate content type and size again in your model.

      Complete example

      A project with several documents, using the ViewComponent. When validation fails, the form comes back with the error under the field and the files that are already stored; files that never reached storage are left out, because the browser can't put them back in a file input.

      class Project < ApplicationRecord
        ACCEPTED_TYPES = %w[application/pdf image/png image/jpeg].freeze
      
        has_many_attached :documents
        validate :acceptable_documents
      
        private
      
        def acceptable_documents
          documents.each do |document|
            errors.add(:documents, "#{document.filename} must be a PDF, PNG or JPG") unless document.content_type.in?(ACCEPTED_TYPES)
            errors.add(:documents, "#{document.filename} is larger than 25 MB") if document.byte_size > 25.megabytes
          end
        end
      end
      
      def update
        @project = Project.find(params[:id])
      
        if @project.update(project_params)
          redirect_to @project, notice: "Project saved."
        else
          render :edit, status: :unprocessable_entity
        end
      end
      
      private
      
      # documents: [] accepts uploaded files and the signed ids of files that stay attached.
      def project_params
        params.expect(project: [:name, documents: []])
      end
      
      <%= form_with model: @project do |form| %>
        <%= form.text_field :name %>
      
        <%= render FileUpload::Component.new(
              name: "project[documents]",
              label: "Documents",
              hint: "PDF, PNG or JPG. Up to 25 MB each.",
              accept: Project::ACCEPTED_TYPES.join(","),
              max_size: 25.megabytes,
              direct_upload: true,
              attachments: @project.documents,
              error: @project.errors.full_messages_for(:documents).to_sentence
            ) %>
      
        <%= form.submit "Save project" %>
      <% end %>
      

      With the shared partial, pass the same options as locals to render "shared/components/file_upload/file_upload". With direct_upload: true, files are stored before the form submits, so a failed validation keeps them too.

      Existing attachments

      Assigning to has_many_attached replaces the whole set, so a form that only submits new files detaches the ones already there. Render each existing attachment as an item with a hidden field holding its signed_id: the files that stay are submitted again, and removing an item removes its field, which detaches that file. form.file_field with multiple: true already adds an empty hidden value first, so removing every item detaches them all.

      <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, put the hidden field after the file input with the same name, and an empty hidden field before it, as in the avatar example. The last value wins: the current signed_id keeps the file, a new pick replaces it, and removing it leaves the empty value, which detaches it.

      Direct uploads

      Active Storage uploads the files one at a time when the form submits and stops at the first error. Every file is queued first and switches to uploading when its own upload starts; files still queued after an error go back to idle. Remove, Clear and Retry are disabled until the form is done (data-uploading is on the controller element meanwhile). A file that finished uploading leaves the input and is kept by the signed_id field Active Storage adds, so Retry only uploads the files that failed or never started, and removing an uploaded file removes that field too.

      Upload as soon as files are picked

      Add data-file-upload-auto-upload-value="true" next to direct_upload: true (or pass auto_upload: true to the ViewComponent) and each file starts uploading the moment it is added, three at a time, with the others queued. The controller fires the same direct-upload:* events Active Storage does, so the states, progress and your own listeners work unchanged, and each finished file is kept by its signed_id field.

      • Removing a file that is still uploading cancels its upload. Retry uploads just that file again.
      • Submitting while files are still uploading waits for them, then submits. If one fails, the form stays put so the user can retry or remove it; a failed file is also back in the input, so submitting anyway tries it once more.
      • @rails/activestorage is only imported when this is turned on, so the controller works without it. Files removed after they finished uploading leave an unattached blob behind; clean those up with ActiveStorage::Blob.unattached in a scheduled job.

      Custom uploaders

      Uploading somewhere else (S3 multipart, a resumable upload service, your own endpoint)? Dispatch the same direct-upload:* events on the input and the list shows the queued, progress, success and error states for you. Call event.preventDefault() on file-upload:retry to retry with your uploader, and listen for file-upload:add and file-upload:remove to start and cancel uploads.

      // data-action="file-upload:add->my-uploader#upload" on the file-upload element
      upload({ target, detail: { files } }) {
        const input = target.querySelector("input[type=file]")
        const emit = (name, detail) =>
          input.dispatchEvent(new CustomEvent(`direct-upload:${name}`, { bubbles: true, cancelable: true, detail }))
      
        files.forEach(async (file, index) => {
          const id = `${Date.now()}-${index}`
          emit("initialize", { id, file })   // item shows "queued"
          emit("start", { id, file })        // "uploading"
          try {
            await myUpload(file, (percent) => emit("progress", { id, file, progress: percent }))
            emit("end", { id, file })        // "success"
          } catch (error) {
            emit("error", { id, file, error: error.message }) // "error", with Retry
          }
        })
      }
      

      To submit the result with the form, insert a hidden field with the input's name right before the input (as Active Storage does), then dispatch end. The controller takes that file out of the input, and removes the field if the file is removed.

      Translations

      Every message the controller writes or announces lives in one table with %{name}-style placeholders. Override it once for the whole app, or per element with the messages value. File sizes use the number format of the nearest lang attribute, so a French page shows “1,5 Mo” once the units are translated.

      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",
      })
      

      Text in your own markup (“Drop files here”, “Waiting…”) is yours to translate with t() as usual. The browser's message for an empty required field is already translated.

      Setup checks

      The controller logs a console warning, and changes nothing, when the markup can't work as intended: a missing or non-file input target, a multiple input whose name doesn't end in [], maxFiles on a single-file input, a template without a list (or the reverse), a template whose first element isn't an item, a status target without aria-live, or a dropzone that opens the picker but can't be reached with the keyboard.

      Browser behavior

      • Required fields. Add required: true to the file field as usual. The browser's own message appears in the error target instead of a bubble pointing at the hidden input, and focus moves to the dropzone or picker button. Any listed file counts, including existing attachments, so editing a record with a required attachment doesn't block the form.
      • Missed drops. While a file upload is on the page, files dropped outside a dropzone are ignored instead of opening in the tab and throwing away the form. Native file inputs and drop handlers that call preventDefault() keep working.
      • Pasting from Office apps. Excel, Numbers, Word and Pages put a picture of the selection on the clipboard along with the text. file-upload#paste lets the text through in that case, and still attaches screenshots and copied files.
      • File types. accept is matched the way browsers match it, and a little more forgivingly: .jpg also accepts .jpeg, files without a MIME type (such as .md, or .heic on Windows) are matched by extension, and a drag is only shown as rejected when the type is known to be wrong. Dropped files are always checked again.
      • Long file names. Add data-truncate="middle" and the flex class to a name field and long names are shortened in the middle, so the extension stays visible. Screen readers still hear the full name, and hovering shows it.
      • Reordering. The input's files follow the order of the items in the list. Move items with any sortable library and the form submits them in the new order.
      • Large photos. Previews decode off the main thread, so dropping a batch of big photos doesn't freeze the page.
      • Turbo. Picked files are cleared right before Turbo caches the page, because a restored file input is always empty. Server-rendered items stay.

      Accessibility

      • The real input stays in the form, so labels, required and form submission work as usual. Point a visible <label for> at it, or give it an aria-label.
      • Give dropzones that open the picker role="button" and tabindex="0". They then open it on click, Enter and Space without any data-action; the actions in the examples do the same and are optional.
      • Buttons and dropzones that open the picker get aria-disabled="true" while the list is full or the input is disabled. They stay focusable, and activating one shows and announces why nothing happens.
      • Error targets are added to the aria-describedby of the input and of those buttons, so the current error is read when they get focus.
      • 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.
      • A role="progressbar" inside an item is hidden from screen readers unless that file is uploading.

      Browser support

      Current Chrome, Edge, Firefox and Safari, on desktop and mobile. Keeping the input in sync with the list needs new DataTransfer() (Chrome 60, Firefox 62, Safari 14.1); in older browsers files can still be picked and submitted, but removing one from the list doesn't take it out of the input. On iOS and Android the picker also offers the camera and photo library. Dropping files works wherever the system supports dragging files into the browser, including iPadOS.

      Troubleshooting

      • Only the last file arrives. A multiple input's name must end in [] (form.file_field … multiple: true does this for you), and the controller's strong params need documents: [].
      • Saving the form removes files that were already attached. Assigning has_many_attached replaces the set. Render existing files with attachments: (or hidden signed_id fields in plain ERB) so they are submitted again.
      • The page crashes when the form is shown again after a validation error. Hand-written items call signed_id on files that were never saved. Skip attachments whose blob.new_record? is true; the ViewComponent and partial already do.
      • No progress bars. Progress needs direct_upload: true on the input and Active Storage's JavaScript (ActiveStorage.start()), plus CORS on your storage bucket.
      • Nothing happens when clicking the dropzone. It needs role="button" (or the file-upload#open action), and the input must not be disabled. Check the console: the controller warns about setup mistakes.
      • Previews don't show for HEIC photos. Only browsers that can display the format show a thumbnail (Safari can); the others show the file icon. The file still uploads.

      Configuration

      Controller Values

      All values belong on the element with data-controller="file-upload". Whether one or several files are allowed comes from the input's own multiple attribute.

      Value Type Default Description
      maxFiles Number 0 Maximum number of files, counting server-rendered items. 0 means no limit.
      maxSize Number 0 Maximum size per file in bytes, for example 5242880 for 5 MB. 0 means no limit.
      accept String "" Accepted types such as .pdf,image/*. Falls back to the input's accept attribute. Files without a MIME type are matched by extension, and .jpg also accepts .jpeg.
      autoUpload Boolean false Direct-upload each file as soon as it is added instead of when the form submits. Needs direct_upload: true on the input.
      messages Object {} Overrides for the controller's messages, as JSON. See Translations.

      Targets

      Target Description
      input Required. The real file input. Its file list always matches the files shown.
      dropzone Accepts dropped files and gets data-drag="accept" or "reject" while files hover over it.
      list Container that receives one item per file.
      template A <template> whose first element is cloned for each file.
      item A file in the list. Server-rendered items are counted and can be removed too.
      error Receives validation messages. Keep it hidden by default.
      status Screen-reader-only aria-live region for added, removed, uploaded and error announcements.
      count Receives the current number of files.

      Item fields and state

      Inside the template, mark elements with data-file-upload-field and the controller fills them in. Style states with Tailwind's group-data-* variants.

      • name, size, extension and percent receive text. Add data-truncate="middle" to a name field to keep the extension visible on long names. error receives the upload error message.
      • preview is an <img> that shows a thumbnail for images and is hidden for other files.
      • bar gets its width set to the progress. ring is an SVG circle with pathLength="100" whose stroke offset follows the progress.
      • remove and retry get an accessible label that includes the file name, such as “Remove report.pdf”.
      • Each item has data-state (idle, queued, uploading, success, error) and data-kind (image, pdf, doc, sheet, archive, video, audio, code, file).
      • The controller element has data-has-files when the list isn't empty, data-uploading while the form's direct uploads run (not set by autoUpload, which leaves the list editable), and data-full when maxFiles is reached.

      Actions and Events

      Name Type Description
      file-upload#open Action Opens the file picker. Use it on a button. Dropzones with role="button" open it on their own.
      file-upload#remove Action Removes the item the button belongs to and moves focus to the next file.
      file-upload#clear Action Removes every file.
      file-upload#retry Action Retries a failed upload. With direct uploads it submits the form again, which only uploads the files that failed or never started.
      file-upload#paste Action Adds files from the clipboard. Bind it to the paste event of a text area or of the whole element.
      file-upload:add Event Dispatched after files pass validation and are added, with event.detail.files and event.detail.elements.
      file-upload:remove Event Dispatched for each removed item, with event.detail.file (null for server-rendered items), event.detail.element and event.detail.replaced (true when a single-file input swaps its file).
      file-upload:change Event Dispatched whenever the files change, in list order, with event.detail.files.
      file-upload:reject Event Dispatched when files fail validation, with event.detail.errors.
      file-upload:retry Event Dispatched by file-upload#retry with event.detail.file and event.detail.element. Call event.preventDefault() to handle the retry yourself instead of resubmitting the form.
      direct-upload:* Event (listened) initialize, start, progress, error and end, dispatched on the input by Active Storage, by autoUpload or by your own uploader, with event.detail.id and event.detail.file. They drive each item's state and progress.

      Table of contents

      Powered by

      Get notified when new components come out