# File upload

Select local files and check the selection.

## Preview

file-upload-preview-1.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = starter;
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-preview-1.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

## Design guidance

Use File Upload when a task needs a custom file trigger, a drop area or the same client checks for both. Use [Input](/components/input) with type="file" for a plain native file form. Use [Attachment](/components/attachment) for file rows, previews, progress and file actions.

File Upload selects files. The caller keeps the native File objects, adds stable IDs, and owns upload, cancellation, storage and AI processing. The Preview starts with sample rows; new selections stay in this browser. No file is sent to a server.

Show the accepted types, size limit and remaining capacity near intake. Render each rejection with its filename and reason. Keep valid files when another file fails. Give Root an accessible name and connect helper/error text with aria-describedby.

In a form, use Field's label and helper parts for the name and count. Keep the instruction separate from the “Browse files” action. Use a description-only Banner with a close icon for rejected files; closing it keeps accepted files.

**Also known as**

Dropzone, Drop zone.

A dropzone is the drag-and-drop region within File upload. Compose FileUpload.Dropzone with a file-picker trigger so people can also choose files without dragging.

## Installation

```sh
npx shadcn@latest add https://ghost-ui.com/r/file-upload.json
```

The file-row and rejection examples also use Attachment and Banner:

```sh
npx shadcn@latest add https://ghost-ui.com/r/attachment.json
```

```sh
npx shadcn@latest add https://ghost-ui.com/r/banner.json
```

Registry source includes the native-input and React Aria integration. Package users import FileUpload from @collectivecreation/ghost-ui/components and load the shared package styles.

## Basic usage

Root supplies acquisition settings. Input is required. Trigger opens that input. Dropzone is optional. Keep selection.accepted in application state and display selection.rejected. Pass the current total as selectedCount when maxFiles limits the full selection.

file-upload-basic-usage-2.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-basic-usage-2.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

## Structures

- FileUpload.Root
  - FileUpload.Input
  - FileUploadHeader (caller label and count)
  - FileUpload.Dropzone (optional)
    - FileUploadContent (caller content)
    - FileUpload.Trigger
  - FileUploadFeedback (caller rejection feedback)
  - AttachmentList (optional)
    - Attachment

Trigger can also sit outside Dropzone, under the same Root. Do not nest Trigger inside another button. Compose a custom Ghost control with its render prop. Root does not own an accepted-file queue or a duplicate Attachment API.

## Examples

### Compact intake

Use inline layout when the surrounding task provides the context. Density controls spacing independently of layout.

file-upload-compact-intake-3.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"compact"}
          layout={"inline"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-compact-intake-3.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

### Trigger only

A drop area is not required for adding files to an existing task.

file-upload-trigger-only-4.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = starter.slice(0, 1);
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${""}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          {null}
        </div>
        <div className="file-upload-example__inline">
          {choose}
          <Field.Description id={`${id}-help`}>
            {"PDF, TXT or CSV \xB7 Up to 20 MB each"}
          </Field.Description>
        </div>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-trigger-only-4.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

### Single-file replacement

With multiple={false}, the caller replaces its file after a valid selection. Cancelling the picker or rejecting a replacement leaves the old file intact.

file-upload-single-file-replacement-5.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = starter.slice(0, 1);
  const selection = useSelectedFiles(initial, 5, true);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${""}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={false}
        maxFiles={1}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Source document"}
          </Field.Label>
          {null}
        </div>
        <div className="file-upload-example__inline">
          {choose}
          <Field.Description id={`${id}-help`}>
            {"One PDF, TXT or CSV \xB7 Up to 20 MB"}
          </Field.Description>
        </div>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-single-file-replacement-5.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

### Image references

Compose existing vertical Attachments. The caller creates local image URLs and revokes them on removal, replacement and unmount.

Image cards use the shared theme corner recipe. The inner radius is the outer radius minus the full inset, including the border. File details stay below the image. The glass remove button floats at the top right.

file-upload-image-references-6.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = [
    {
      view: {
        id: "workspace",
        name: "Workspace.jpg",
        mediaType: "image/jpeg",
        size: 493568,
        url: "/attachments/desk.jpg",
      },
    },
    {
      view: {
        id: "team",
        name: "Team space.jpg",
        mediaType: "image/jpeg",
        size: 753664,
        url: "/attachments/office.jpg",
      },
    },
  ];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={"image/png,image/jpeg,image/webp"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Visual references"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose an image or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PNG, JPG or WebP \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={"file-upload-example__images"}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={view.url ? <img src={view.url} alt="" /> : undefined}
                  size={"default"}
                  orientation={"vertical"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-image-references-6.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

### In a message draft

Compose FileUpload.Trigger with Composer. This example prepares a local draft; it does not contact a model.

Keep the plus action, draft and file feedback inside Composer.

file-upload-in-a-message-draft-7.jsx

```jsx
import * as React from "react";
import { Plus } from "lucide-react";
import { FileUpload } from "@/components/ui/file-upload";
import { Button } from "@/components/ui/button";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";
import {
  Composer,
  ComposerInput,
  ComposerToolbar,
  ComposerSubmit,
  ComposerAttachments,
} from "@/components/ui/composer";

export default function Example() {
  const selection = useSelectedFiles(starter.slice(0, 1), 5);
  const id = React.useId();
  const trigger = React.useRef(null);
  const [message, setMessage] = React.useState("");
  return (
    <Field.Root className="file-upload-example">
      <FileUpload.Root
        multiple
        selectedCount={selection.files.length}
        maxFiles={5}
        maxFileSize={20971520}
        aria-label="Message files"
        aria-describedby={
          selection.rejected.length ? `${id}-errors` : undefined
        }
        onFilesSelect={selection.select}
      >
        <FileUpload.Input />
        <Composer
          aria-label="Message draft"
          defaultValue="Find the main themes in these interviews."
          attachments={selection.files.map((record) => record.view)}
          attachmentContent={
            <ComposerAttachments onRemove={selection.remove} />
          }
          onSubmit={() => {
            setMessage("The draft and its files are ready to send.");
          }}
        >
          <ComposerInput />
          <ComposerToolbar>
            <ComposerToolbar.Start>
              <FileUpload.Trigger
                ref={trigger}
                render={
                  <Button variant="ghost" leadingIcon={<Plus size={14} />} />
                }
              >
                Add files
              </FileUpload.Trigger>
            </ComposerToolbar.Start>
            <ComposerToolbar.End>
              <ComposerSubmit />
            </ComposerToolbar.End>
          </ComposerToolbar>
          <SelectionErrors
            id={`${id}-errors`}
            rejected={selection.rejected}
            focusRef={trigger}
            onDismiss={selection.dismiss}
          />
          {message ? <span role="status">{message}</span> : null}
        </Composer>
      </FileUpload.Root>
    </Field.Root>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-in-a-message-draft-7.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}

```

### Form submission

Build FormData from the caller's current native files. The hidden acquisition input does not serialize the accumulated selection. This example prepares the import locally; send the FormData through your own transport.

file-upload-form-submission-8.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment } from "@/components/ui/attachment";
import { Button } from "@/components/ui/button";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const selection = useSelectedFiles([], 1, true);
  const [message, setMessage] = React.useState("");
  const id = React.useId();
  const trigger = React.useRef(null);
  return (
    <form
      className="file-upload-example"
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData();
        for (const record of selection.files)
          if (record.native) data.append("files", record.native);
        const selected = data.get("files");
        setMessage(
          selected instanceof File
            ? `${selected.name} is ready to import.`
            : "Choose a CSV file.",
        );
      }}
    >
      <Field.Root invalid={selection.rejected.length > 0}>
        <FileUpload.Root
          aria-labelledby={id}
          aria-describedby={`${id}-help${selection.rejected.length ? ` ${id}-errors` : ""}`}
          accept=".csv"
          maxFileSize={20971520}
          onFilesSelect={(result) => {
            selection.select(result);
            setMessage("");
          }}
        >
          <Field.Label id={id} htmlFor={`${id}-trigger`}>
            Import customer feedback
          </Field.Label>
          <FileUpload.Input />
          <FileUpload.Dropzone>
            <span>Choose a CSV file or drop it here</span>
            <FileUpload.Trigger
              ref={trigger}
              id={`${id}-trigger`}
              aria-label="Browse files"
            >
              Browse files
            </FileUpload.Trigger>
            <span id={`${id}-help`} className="ui-caption">
              CSV · Up to 20 MB
            </span>
          </FileUpload.Dropzone>
          <SelectionErrors
            id={`${id}-errors`}
            rejected={selection.rejected}
            focusRef={trigger}
            onDismiss={selection.dismiss}
          />
          {selection.files.map(({ view }) => (
            <Attachment
              key={view.id}
              file={view}
              onRemove={(file) => {
                selection.remove(file);
                setMessage("");
                restoreFocus(trigger);
              }}
            />
          ))}
          <div className="file-upload-example__submit">
            <Button
              type="submit"
              variant="solid"
              disabled={!selection.files.length}
            >
              Prepare import
            </Button>
          </div>
          {message ? <span role="status">{message}</span> : null}
        </FileUpload.Root>
      </Field.Root>
    </form>
  );
}

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-form-submission-8.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}

```

### Subtle surface

Use the shared Input surface appearance without changing selection behavior.

file-upload-subtle-surface-9.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"subtle"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-subtle-surface-9.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

### Selection limits and recovery

Rejected files do not use a slot. Close the error banner to clear feedback and return to the picker. Accepted files remain. A new completed selection replaces the previous rejection feedback. Picker cancellation keeps it.

file-upload-selection-limits-and-recovery-10.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = starter.slice(0, 1);
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(true);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-selection-limits-and-recovery-10.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

At capacity, intake stops while existing Remove actions remain available.

file-upload-selection-limits-and-recovery-11.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = [
    ...starter,
    ...["Product brief.pdf", "Research plan.txt", "Support themes.csv"].map(
      (name, index) => ({
        view: {
          id: `sample-${index}`,
          name,
          size: 24576,
        },
      }),
    ),
  ];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-selection-limits-and-recovery-11.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

Disabled intake keeps its label and helper text readable.

file-upload-selection-limits-and-recovery-12.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={true}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {"File uploads are disabled for this project"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        {false}
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

```

file-upload-selection-limits-and-recovery-12.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

### Long filenames

Use Attachment's compact size in a constrained row. Its full filename remains available to the Tooltip and accessible actions.

file-upload-long-filenames-13.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const initial = [
    {
      view: {
        ...starter[0].view,
        name: "Customer_interview_findings_and_product_recommendations_November_2026.pdf",
      },
    },
  ];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${" file-upload-example--narrow"}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"sm"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

```

file-upload-long-filenames-13.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

### Transfer and processing states

These are controlled state examples. Retry moves the file back to Uploading; Cancel stops that state. The examples make no network request. In an application, wire these callbacks to its transfer. Report a percentage only when the transport supplies a known total. Attachment uses Progress.Background, so its status stays over the fill without a separate meter row. The glass actions float at the end of the file row.

file-upload-transfer-and-processing-states-14.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const [file, setFile] = React.useState(() => ({
    ...starter[0].view,
    status: "uploading",
    progress: 64,
    error: undefined,
  }));
  const root = React.useRef(null);
  return (
    <div ref={root} className="file-upload-example">
      {file ? (
        <Attachment
          file={file}
          aria-busy={file.status === "uploading" || undefined}
          onRemove={() => {
            setFile(null);
            restoreFocus(root);
          }}
          onCancel={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "cancelled",
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
          onRetry={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "uploading",
                  error: undefined,
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
        >
          {null}
        </Attachment>
      ) : (
        <FileUploadExample variant="empty" />
      )}
    </div>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

function FileUploadExample({ variant = "default" }) {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

```

file-upload-transfer-and-processing-states-14.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

Unknown progress uses Progress.Background with value={null} and no percentage. Its shimmer travels from left to right on a steady cycle.

file-upload-transfer-and-processing-states-15.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const [file, setFile] = React.useState(() => ({
    ...starter[0].view,
    status: "uploading",
    progress: undefined,
    error: undefined,
  }));
  const root = React.useRef(null);
  return (
    <div ref={root} className="file-upload-example">
      {file ? (
        <Attachment
          file={file}
          aria-busy={file.status === "uploading" || undefined}
          onRemove={() => {
            setFile(null);
            restoreFocus(root);
          }}
          onCancel={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "cancelled",
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
          onRetry={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "uploading",
                  error: undefined,
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
        >
          {null}
        </Attachment>
      ) : (
        <FileUploadExample variant="empty" />
      )}
    </div>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

function FileUploadExample({ variant = "default" }) {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

```

file-upload-transfer-and-processing-states-15.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

Failure and cancellation preserve the file and offer the actions supported by Attachment.

file-upload-transfer-and-processing-states-16.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const [file, setFile] = React.useState(() => ({
    ...starter[0].view,
    status: "error",
    progress: undefined,
    error: "Connection lost. Try again.",
  }));
  const root = React.useRef(null);
  return (
    <div ref={root} className="file-upload-example">
      {file ? (
        <Attachment
          file={file}
          aria-busy={file.status === "uploading" || undefined}
          onRemove={() => {
            setFile(null);
            restoreFocus(root);
          }}
          onCancel={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "cancelled",
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
          onRetry={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "uploading",
                  error: undefined,
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
        >
          {null}
        </Attachment>
      ) : (
        <FileUploadExample variant="empty" />
      )}
    </div>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

function FileUploadExample({ variant = "default" }) {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

```

file-upload-transfer-and-processing-states-16.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

file-upload-transfer-and-processing-states-17.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";

export default function Example() {
  const [file, setFile] = React.useState(() => ({
    ...starter[0].view,
    status: "cancelled",
    progress: undefined,
    error: undefined,
  }));
  const root = React.useRef(null);
  return (
    <div ref={root} className="file-upload-example">
      {file ? (
        <Attachment
          file={file}
          aria-busy={file.status === "uploading" || undefined}
          onRemove={() => {
            setFile(null);
            restoreFocus(root);
          }}
          onCancel={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "cancelled",
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
          onRetry={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "uploading",
                  error: undefined,
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
        >
          {null}
        </Attachment>
      ) : (
        <FileUploadExample variant="empty" />
      )}
    </div>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

function FileUploadExample({ variant = "default" }) {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

```

file-upload-transfer-and-processing-states-17.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

Upload completion does not establish that an AI file is usable. This example composes the same processing Progress.Background and caller-owned feedback through Attachment's children.

file-upload-transfer-and-processing-states-18.jsx

```jsx
import * as React from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { Attachment, AttachmentList } from "@/components/ui/attachment";
import { Banner } from "@/components/ui/banner";
import { Field } from "@/components/ui/field";
import { Progress } from "@/components/ui/progress";

export default function Example() {
  const [file, setFile] = React.useState(() => ({
    ...starter[0].view,
    status: "ready",
    progress: undefined,
    error: undefined,
  }));
  const root = React.useRef(null);
  return (
    <div ref={root} className="file-upload-example">
      {file ? (
        <Attachment
          file={file}
          aria-busy={true}
          onRemove={() => {
            setFile(null);
            restoreFocus(root);
          }}
          onCancel={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "cancelled",
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
          onRetry={() => {
            setFile(
              (current) =>
                current && {
                  ...current,
                  status: "uploading",
                  error: undefined,
                  progress: undefined,
                },
            );
            restoreFocus(root);
          }}
        >
          <>
            <Progress.Background
              value={null}
              label={`Processing ${file.name}`}
            />
            <span className="file-upload-example__processing">Processing…</span>
          </>
        </Attachment>
      ) : (
        <FileUploadExample variant="empty" />
      )}
    </div>
  );
}

var starter = [
  {
    view: {
      id: "interviews",
      name: "Interview notes.pdf",
      mediaType: "application/pdf",
      size: 2516582,
    },
  },
  {
    view: {
      id: "survey",
      name: "Survey results.csv",
      mediaType: "text/csv",
      size: 188416,
    },
  },
];

function useSelectedFiles(initial, maxFiles, single = false) {
  const [files, setFiles] = React.useState(initial);
  const [rejected, setRejected] = React.useState([]);
  const current = React.useRef(files);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const sequence = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const commit = (next) => {
    current.current = next;
    setFiles(next);
  };
  const release = (file) => {
    if (file.view.url && urls.current.delete(file.view.url))
      URL.revokeObjectURL(file.view.url);
  };
  const select = (selection) => {
    const available = single
      ? 1
      : Math.max(0, maxFiles - current.current.length);
    const accepted = selection.accepted.slice(0, available);
    const overflow = selection.accepted.slice(available).map((file) => ({
      file,
      name: file.name,
      errors: [
        {
          code: "file-count",
          message: "Remove a file to add another.",
        },
      ],
    }));
    setRejected([...selection.rejected, ...overflow]);
    const added = accepted.map((native) => {
      const id = `selected-${++sequence.current}`;
      const url =
        /^(image\/(png|jpeg|webp|gif|avif))$/.test(native.type) &&
        typeof URL.createObjectURL === "function"
          ? URL.createObjectURL(native)
          : undefined;
      if (url) urls.current.add(url);
      return {
        native,
        view: {
          id,
          name: native.name,
          mediaType: native.type,
          size: native.size,
          url,
        },
      };
    });
    if (!added.length) return;
    if (single) current.current.forEach(release);
    commit(single ? added : [...current.current, ...added]);
  };
  const remove = (file) => {
    const found = current.current.find((item) => item.view.id === file.id);
    if (found) release(found);
    commit(current.current.filter((item) => item.view.id !== file.id));
  };
  return {
    files,
    rejected,
    select,
    remove,
    dismiss: () => setRejected([]),
  };
}

function restoreFocus(ref) {
  requestAnimationFrame(() => {
    const node = ref.current;
    if (!node) return;
    const target =
      node instanceof HTMLButtonElement && !node.disabled
        ? node
        : (node.closest(".ui-file-upload") ?? node).querySelector(
            "button:not(:disabled):not(.ui-sr-only)",
          );
    target?.focus();
  });
}

function SelectionErrors({ rejected, onDismiss, id, focusRef }) {
  if (!rejected.length) return null;
  return (
    <Banner
      id={id}
      className="file-upload-example__errors"
      tone="danger"
      icon={null}
      width="fill"
      role="note"
      dismissLabel="Dismiss file errors"
      onDismiss={() => {
        onDismiss();
        restoreFocus(focusRef);
      }}
    >
      {rejected.map((item, index) => (
        <React.Fragment key={`${item.name}-${index}`}>
          {index ? <br /> : null}
          {item.name}
          {": "}
          {item.errors.map((error) => error.message).join(" ")}
        </React.Fragment>
      ))}
    </Banner>
  );
}

function FileUploadExample({ variant = "default" }) {
  const initial = [];
  const selection = useSelectedFiles(initial, 5, false);
  const [showSampleErrors, setShowSampleErrors] = React.useState(false);
  const id = React.useId();
  const trigger = React.useRef(null);
  const count = selection.files.length;
  const errors = showSampleErrors
    ? [
        {
          name: "Customer_interview_recording_November_2026.mov",
          errors: [
            {
              code: "file-type",
              message: "Use a PDF, TXT or CSV file.",
            },
          ],
        },
        {
          name: "Findings.pdf",
          errors: [
            {
              code: "file-size",
              message: "The file exceeds 20 MB.",
            },
          ],
        },
      ]
    : selection.rejected;
  const choose = (
    <FileUpload.Trigger
      ref={trigger}
      id={`${id}-trigger`}
      aria-label="Browse files"
    >
      Browse files
    </FileUpload.Trigger>
  );
  const remove = (file) => {
    selection.remove(file);
    restoreFocus(trigger);
  };
  return (
    <Field.Root
      invalid={errors.length > 0}
      className={`file-upload-example${""}`}
    >
      <FileUpload.Root
        aria-labelledby={`${id}-label`}
        aria-describedby={`${id}-help${` ${id}-count`}${errors.length ? ` ${id}-errors` : ""}`}
        accept={".pdf,.txt,.csv"}
        multiple={true}
        maxFiles={5}
        selectedCount={count}
        maxFileSize={20971520}
        disabled={false}
        onFilesSelect={(result) => {
          setShowSampleErrors(false);
          selection.select(result);
        }}
      >
        <FileUpload.Input />
        <div className="file-upload-example__heading">
          <Field.Label id={`${id}-label`} htmlFor={`${id}-trigger`}>
            {"Research sources"}
          </Field.Label>
          <Field.Description
            id={`${id}-count`}
            className="file-upload-example__count"
          >
            {count}
            {" of 5 files"}
          </Field.Description>
        </div>
        <FileUpload.Dropzone
          density={"default"}
          layout={"stacked"}
          variant={"outline"}
        >
          {(state) => (
            <>
              <span>
                {state.rejected
                  ? "This file type is not supported"
                  : state.dragging
                    ? "Drop files to add"
                    : state.pending
                      ? "Reading files\u2026"
                      : "Choose a file or drop it here"}
              </span>
              {choose}
              <Field.Description id={`${id}-help`}>
                {count === 5
                  ? "Remove a file to add another"
                  : "PDF, TXT or CSV \xB7 20 MB each"}
              </Field.Description>
            </>
          )}
        </FileUpload.Dropzone>
        <SelectionErrors
          id={`${id}-errors`}
          rejected={errors}
          focusRef={trigger}
          onDismiss={() => {
            setShowSampleErrors(false);
            selection.dismiss();
          }}
        />
        {count ? (
          <AttachmentList
            aria-label="Selected research files"
            className={undefined}
          >
            {selection.files.map(({ view }) => (
              <li key={view.id}>
                <Attachment
                  file={view}
                  media={undefined}
                  size={"default"}
                  orientation={"horizontal"}
                  onRemove={remove}
                />
              </li>
            ))}
          </AttachmentList>
        ) : null}
      </FileUpload.Root>
    </Field.Root>
  );
}

```

file-upload-transfer-and-processing-states-18.css

```css
/* apps/web/src/demos/library/file-upload.css */
.file-upload-example {
  width: min(100%, 460px);
  min-width: 0;
}
.file-upload-example__heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-3);
}
.file-upload-example__count {
  flex-shrink: 0;
}
.file-upload-example__inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-3);
}
.file-upload-example__errors {
  overflow-wrap: anywhere;
}
.file-upload-example__images {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.file-upload-example__processing {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1);
  color: var(--muted-foreground);
  font-size: var(--font-size-caption);
}
.file-upload-example__submit {
  display: flex;
  justify-content: flex-end;
}
.file-upload-example--narrow {
  max-width: 288px;
}
@media (max-width: 360px) {
  .file-upload-example__images {
    grid-template-columns: minmax(0, 1fr);
  }
}

```

## API reference

### Root

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| onFilesSelect (required) | (selection: FileUploadSelection) => void | — | Receives accepted native files, named rejections and picker/drop source once per nonempty batch. The caller commits the files. |
| accept | string | undefined | Native MIME, wildcard or extension list. The same rules check picker and drop files. This is client feedback, not content verification. |
| multiple | boolean | false | Accept one replacement candidate or multiple files. |
| maxFiles | number | 1 for single; unbounded for multiple | Maximum file count. For multiple selection, subtract selectedCount and accept the valid prefix. Zero disables intake. |
| selectedCount | number | 0 | Current caller selection count. A single-file replacement does not count its existing file against the new candidate. |
| maxFileSize | number | undefined | Per-file byte limit. Explicit limits must be finite and nonnegative. Counts are safe integers. Zero-byte files are allowed unless caller validation rejects them. |
| validate | (file: File) => readonly FileUploadError[] \| undefined | — | Optional synchronous application checks. Runs after type/size checks. An exception rejects that file without exposing the exception text. |
| disabled | boolean | false | Blocks acquisition and invalidates pending results. Caller file actions remain independent. |
| ref / native attributes | HTMLDivElement / HTMLAttributes | — | Forwarded to the labelled group. Use aria-labelledby and aria-describedby for visible label/help/error associations. |

FileUploadSelection is { accepted: File[], rejected: FileUploadRejection[], source: "picker" | "drop" }. A rejection has { name, file?, errors: { code, message }[] }. A directory or read failure can have no File. Built-in codes are file-type, file-size, file-count, directory, file-read, and validation-failed; custom checks can supply their own codes.

Files retain their identity and order. No deduplication by name occurs. If another intake can change the same queue, recheck total capacity in the caller's atomic commit. Remount Root to discard pending work when resetting the whole task.

### Input and Trigger

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| Input (required) | FileUpload.Input | — | One hidden native acquisition input per Root. Forwards its input ref and safe acquisition attributes such as capture. Root owns type, accept, multiple, disabled and change handling. |
| Input form attributes | unsupported | — | name, required, value and defaultValue do not represent the managed queue. Use native Input for native file-form serialization, or submit caller FormData. |
| Trigger | FileUpload.Trigger | — | A real Ghost outline Button by default. Always type=button. Clears the acquisition input before opening so the same file can be selected again. |
| Trigger render / ref | useRender render / HTMLButtonElement | — | Compose a custom control with merged props and refs. Caller preventDefault cancels opening. Disabled Root cannot be re-enabled through the trigger. |

### Dropzone

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| variant | "outline" \| "subtle" | "outline" | Shared Input.Surface appearance with an owned dashed boundary and drag feedback. |
| layout | "stacked" \| "inline" | "stacked" | Stack the intake content or arrange it in a wrapping row. |
| density | "default" \| "compact" | "default" | Standard or compact content inset. Independent of layout. |
| children | ReactNode \| (state) => ReactNode | — | State contains dragging, rejected, disabled and pending. Show an instruction for the current intake state. |
| ref / native attributes | HTMLDivElement / HTMLAttributes | — | Forwarded to the shared surface. Native drop prevention stays inside this area; no document-wide file-drop handler is installed. |

React Aria owns drop interaction. The hidden accessible drop target does not add a normal tab stop. The visible Trigger is the native file-picker path. Pre-drop metadata can be incomplete: only show rejection when it is known, then validate actual files after drop. Folders and non-file URL/text drops are not imported.

The caller owns server validation, authorization, safe storage, local preview URL lifetime and transfer cancellation. Client accept, MIME and filenames cannot prove file contents or upload safety.
