# File Upload

A drag-and-drop file selection recipe powered by react-dropzone with validation, browse controls, and File Card composition.

File Upload handles file selection through drag and drop, paste, or a native file picker. It validates file type, size, and count before handing accepted files to application state.

<p className="zenos-recipe-source">
  Powered by <a href="https://react-dropzone.js.org/">react-dropzone</a> for file extraction, drag
  state, picker behavior, and validation. Zenos owns the compound anatomy, density, semantic
  styling, and composition with File Card.
</p>

```bash
pnpm dlx @zentara-co/zenos-cli add file-upload
npx @zentara-co/zenos-cli add file-upload
yarn dlx @zentara-co/zenos-cli add file-upload
bunx @zentara-co/zenos-cli add file-upload
```

The command installs `react-dropzone` and adds `file-upload.tsx` to the consumer project. Import the editable recipe through the path configured by your application:

```tsx
import { FileUpload } from "./components/file-upload";
```

## Basic usage

The root owns react-dropzone and renders the hidden native file input. Dropzone is a visual drop target rather than a button. Include `FileUpload.Link` or `FileUpload.Trigger` to provide an explicit keyboard-accessible path to the file picker.

```tsx
import { FileArrowUpIcon, TrashIcon } from "@phosphor-icons/react";
import { useState } from "react";
import { FileCard, IconButton, fileTypeFromName } from "@zentara-co/zenos-ui";
import { FileUpload, formatBytes } from "@docs/src/recipes/file-upload/file-upload";

function FileUploadRecipeExample() {
  const [files, setFiles] = useState<File[]>([]);
  const [error, setError] = useState("");

  return (
    <FileUpload.Root
      accept={{
        "image/*": [".jpg", ".jpeg", ".png", ".webp"],
        "application/pdf": [".pdf"],
      }}
      maxFiles={4}
      maxSize={5 * 1024 * 1024}
      invalid={Boolean(error)}
      onFiles={(accepted) => {
        setError("");
        setFiles((current) => [...current, ...accepted]);
      }}
      onReject={(rejections) => setError(rejections[0]?.errors[0]?.message ?? "File rejected")}
      className="w-full max-w-2xl"
    >
      <FileUpload.Dropzone>
        <FileUpload.Icon>
          <FileArrowUpIcon />
        </FileUpload.Icon>
        <FileUpload.Title>
          Drop files here, or <FileUpload.Link>browse</FileUpload.Link>
        </FileUpload.Title>
        <FileUpload.Description>Images or PDF files, up to 5 MB each</FileUpload.Description>
      </FileUpload.Dropzone>

      {error && <FileUpload.Error>{error}</FileUpload.Error>}

      {files.length > 0 && (
        <FileUpload.List aria-label="Selected files">
          {files.map((file, index) => (
            <FileCard key={`${file.name}-${file.lastModified}-${index}`} density="compact">
              <FileCard.Icon type={fileTypeFromName(file.name)} />
              <FileCard.Content>
                <FileCard.Name>{file.name}</FileCard.Name>
                <FileCard.Meta>{formatBytes(file.size)}</FileCard.Meta>
              </FileCard.Content>
              <FileCard.Actions>
                <IconButton
                  aria-label={`Remove ${file.name}`}
                  size="sm"
                  variant="ghost"
                  onClick={() => setFiles((current) => current.filter((_, item) => item !== index))}
                >
                  <TrashIcon />
                </IconButton>
              </FileCard.Actions>
            </FileCard>
          ))}
        </FileUpload.List>
      )}
    </FileUpload.Root>
  );
}
```

```text
FileUpload.Root
├── FileUpload.Dropzone
│   ├── FileUpload.Icon
│   ├── FileUpload.Title
│   │   └── FileUpload.Link
│   ├── FileUpload.Description
│   └── FileUpload.Trigger
├── FileUpload.Error
├── FileUpload.Sources
│   └── FileUpload.Source
├── FileUpload.List
│   └── FileCard
└── FileUpload.Grid
    └── FileCard
```

File Upload does not store files or send network requests. `onFiles` receives accepted `File` objects; keep them in feature state, render them with [File Card](/components/file-card/), and pass them to the upload service owned by that feature.

## Accepted file types

Use react-dropzone's MIME-to-extension object when the product has a strict contract. It gives the browser both MIME and extension hints:

```tsx
<FileUpload.Root
  accept={{
    "image/*": [".jpg", ".jpeg", ".png", ".webp"],
    "application/pdf": [".pdf"],
  }}
  onFiles={setFiles}
>
  {/* dropzone */}
</FileUpload.Root>
```

For simple cases, the recipe also accepts an HTML-style string such as `".pdf,.doc,.docx"`. A file extension is only a client-side hint; validate MIME type, content, size, and authorization again on the server before persisting an upload.

## Validation

`accept`, `minSize`, `maxSize`, `maxFiles`, `multiple`, and `validator` are passed to react-dropzone. Accepted files go to `onFiles`. Rejected files go to `onReject` as react-dropzone `FileRejection` objects, each containing the original file and one or more typed errors.

```tsx
import { useState } from "react";
import { Text } from "@zentara-co/zenos-ui";
import { FileUpload } from "@docs/src/recipes/file-upload/file-upload";

function FileUploadValidationExample() {
  const [error, setError] = useState("");
  const [status, setStatus] = useState("Select one PDF up to 2 MB.");

  return (
    <FileUpload.Root
      accept={{ "application/pdf": [".pdf"] }}
      invalid={Boolean(error)}
      maxFiles={1}
      maxSize={2 * 1024 * 1024}
      multiple={false}
      onFiles={(files) => {
        setError("");
        setStatus(`${files[0]?.name ?? "File"} is ready to upload.`);
      }}
      onReject={(rejections) => {
        setError(rejections[0]?.errors.map((issue) => issue.message).join(" ") ?? "File rejected.");
        setStatus("");
      }}
      className="w-full max-w-xl"
    >
      <FileUpload.Dropzone>
        <FileUpload.Icon />
        <FileUpload.Title>
          Drop a PDF here, or <FileUpload.Link />
        </FileUpload.Title>
        <FileUpload.Description>Single PDF file, up to 2 MB</FileUpload.Description>
      </FileUpload.Dropzone>
      {error ? (
        <FileUpload.Error>{error}</FileUpload.Error>
      ) : (
        <Text size="s" color="subtle" aria-live="polite">
          {status}
        </Text>
      )}
    </FileUpload.Root>
  );
}
```

Show a concise rejection near the dropzone and keep it in an `aria-live="polite"` region. When several files fail, summarize the problem first and provide file-level details in the attachment list if the user can act on them independently.

Set `invalid` when a rejection should remain visible. The dropzone then uses the same two-pixel danger border and subtle danger background as an invalid Zenos Input. Render `FileUpload.Error` beside it for the associated alert text; accepting a valid file should clear both the error and `invalid` state.

Custom validators may return a react-dropzone error or a promise. Use them for client-side checks such as image dimensions, but avoid treating them as security boundaries. While an asynchronous validator runs, Dropzone exposes `data-state="processing"`.

## Browse-only trigger

Use `FileUpload.Trigger` without a dropzone when the layout only has room for an attach button. It is a Zenos Button, defaults to `variant="outline"`, and supports the normal Button size, icon, motion, and styling props.

```tsx
import { PaperclipIcon } from "@phosphor-icons/react";
import { useState } from "react";
import { Text } from "@zentara-co/zenos-ui";
import { FileUpload } from "@docs/src/recipes/file-upload/file-upload";

function FileUploadTriggerExample() {
  const [name, setName] = useState<string>();

  return (
    <FileUpload.Root
      accept=".pdf,.doc,.docx"
      multiple={false}
      onFiles={(files) => setName(files[0]?.name)}
      className="w-full max-w-xl"
    >
      <div className="flex flex-wrap items-center gap-3">
        <FileUpload.Trigger size="sm" startIcon={<PaperclipIcon />}>
          Attach file
        </FileUpload.Trigger>
        <Text size="s" color="subtle" aria-live="polite">
          {name ?? "No file selected"}
        </Text>
      </div>
    </FileUpload.Root>
  );
}
```

## File lists and grids

`FileUpload.List` is a vertical layout for attachment rows. `FileUpload.Grid` provides a responsive grid for `FileCard layout="tile"`. Both are layout-only parts: application state decides which files appear, their upload progress, and how removal or retry works.

Use `formatBytes(file.size)` for a concise File Card meta value. For images, create and revoke object URLs in the feature that owns the selected files; the recipe deliberately does not manage URL lifetimes.

## External sources

`FileUpload.Sources` and `FileUpload.Source` can present import options such as Drive, Dropbox, or a repository. A source is a normal button and does not open the native picker. Wire its `onClick` to the provider-specific authorization and picker flow.

```tsx
<FileUpload.Sources>
  <FileUpload.Source label="Google Drive" onClick={openDrivePicker}>
    <DriveMark />
  </FileUpload.Source>
  <FileUpload.Source label="Dropbox" onClick={openDropboxPicker}>
    <DropboxMark />
  </FileUpload.Source>
</FileUpload.Sources>
```

## Density

`density="comfortable"` provides a roomy standalone upload panel. `density="compact"` reduces the dropzone minimum height, padding, spacing, and icon size for forms and side panels. Density inherits from `DensityProvider` when omitted.

```tsx
import { FileUpload } from "@docs/src/recipes/file-upload/file-upload";

function FileUploadDensityExample() {
  return (
    <div className="grid w-full max-w-3xl gap-4 md:grid-cols-2">
      {(["comfortable", "compact"] as const).map((density) => (
        <FileUpload.Root key={density} density={density}>
          <FileUpload.Dropzone>
            <FileUpload.Icon />
            <FileUpload.Title className="capitalize">{density}</FileUpload.Title>
            <FileUpload.Description>Drop files or use the browse control.</FileUpload.Description>
            <FileUpload.Trigger size="sm">Choose files</FileUpload.Trigger>
          </FileUpload.Dropzone>
        </FileUpload.Root>
      ))}
    </div>
  );
}
```

## Disabled state

Set `disabled` on the root when file selection is unavailable. Drag, paste, picker triggers, and source buttons become inert, and the dropzone communicates the disabled state visually and through `aria-disabled`.

```tsx
import { FileUpload } from "@docs/src/recipes/file-upload/file-upload";

function FileUploadDisabledExample() {
  return (
    <FileUpload.Root disabled className="w-full max-w-xl">
      <FileUpload.Dropzone>
        <FileUpload.Icon />
        <FileUpload.Title>Uploads paused</FileUpload.Title>
        <FileUpload.Description>
          You have reached the workspace storage limit.
        </FileUpload.Description>
        <FileUpload.Trigger className="w-full">Upload files</FileUpload.Trigger>
      </FileUpload.Dropzone>
    </FileUpload.Root>
  );
}
```

## Root API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| accept | Accept \| string | — | MIME/extension validation map or comma-separated HTML-style accept string. |
| invalid | boolean | false | Applies the Zenos form-control invalid surface and associates FileUpload.Error. |
| multiple | boolean | true | Allows more than one file in a selection. |
| minSize / maxSize | number | — | Inclusive file-size limits in bytes. |
| maxFiles | number | — | Maximum accepted files in one selection when multiple is enabled. |
| validator | DropzoneOptions['validator'] | — | Synchronous or asynchronous per-file react-dropzone validator. |
| onFiles | (files: readonly File[]) => void | — | Receives accepted files without storing or uploading them. |
| onReject | (rejections: readonly FileRejection[]) => void | — | Receives rejected files and react-dropzone error details. |
| density | comfortable \| compact | comfortable | Dropzone spacing inherited from DensityProvider when omitted. |
| disabled | boolean | false | Disables drop, paste, native picker, triggers, and sources. |
| noDrag / noPaste | boolean | false | Disables an individual react-dropzone input path. |
| inputLabel | string | Choose files | Accessible name for the hidden native file input. |

Root also forwards native `div` attributes and its ref. All parts accept `className`, merge it last, expose stable `data-slot` attributes, and forward the native props and refs for their rendered element.

## Accessibility

The dropzone itself remains a non-interactive `div` because turning a panel containing links and buttons into another button would create nested interactive controls. Always provide `FileUpload.Link` or `FileUpload.Trigger` as the keyboard path to the picker.

- Write the title as an instruction: “Drop files here, or browse.”
- Put accepted formats, maximum size, and count in the description before selection.
- Announce acceptance or rejection without moving focus.
- Give removal, retry, pause, and cancel controls file-specific accessible names.
- Do not rely on drag and drop as the only input method.
- Preserve a visible focus indicator on picker and source controls.

## Review checklist

Before shipping a file-upload flow, verify:

- [ ] A keyboard-accessible browse control is present.
- [ ] Accepted formats, size, and count limits are visible before selection.
- [ ] Client validation is repeated by the server.
- [ ] Rejection messages explain what the user can change.
- [ ] Selected files remain application state rather than hidden recipe state.
- [ ] Object URLs are revoked when previews are removed or unmounted.
- [ ] Upload progress, retry, pause, and cancellation belong to the feature's transport layer.
- [ ] Every icon-only file action has a file-specific accessible name.
- [ ] Disabled state blocks drag, paste, picker, and external source controls.
- [ ] Narrow layouts retain readable filenames and usable action targets.

Source: https://zenos-ui.pages.dev/recipes/file-upload/