---
title: FileUpload
description: Select and validate local files through a drop area or compact button.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# FileUpload

> Select and validate local files through a drop area or compact button.

## Anatomy

```text
FileUpload [component; slot=root]
├── control [slot]
│   └── wrapper [slot]
│       ├── icon [slot]
│       ├── label [slot]
│       └── description [slot]
├── input [internal]
└── files [slot]
    └── file [slot]
        ├── filePreview [slot]
        ├── fileMeta [slot]
        │   ├── fileName [slot]
        │   └── fileSize [slot]
        └── fileRemove [slot]
```

## Usage

Use FileUpload to collect local files before the application sends them. Selection and validation
happen in the component; upload transport belongs to the caller.

```tsx
import { FileUpload } from 'moraine'

export function Example() {
  return <FileUpload label="Upload files" />
}
```

### Selecting files

`variant` sets the appearance: `area` (the default) shows a large dashed drop area, and `button`
shows a compact picker button. Clicking anywhere in the visible control, including its padding, icon,
and text, opens the file picker. `dropzone` (default `true`) only controls whether files can be
dropped onto the control; it does not change how the control looks. File previews and removal
actions are outside the picker hit area.

Use `multiple` when the value can hold more than one `File`. New files are appended to the
selection, and `value` and `onValueChange` use a `File[]`. Without `multiple`, a new file replaces
the current one, and the value is `File | null`.

```tsx
<FileUpload multiple label="Click anywhere or drop files" description="Choose documents and images." />
<FileUpload variant="button" label="Attach files" />
```

### Selected file list

The selected files appear in a list below the control, with an image thumbnail for image files and
`fileIcon` for other types. Set `fileList={false}` to omit the list and render the selection
yourself from `onValueChange`. Use `itemRender` to replace each entry. It receives `file`, `index`,
`previewUrl`, `remove`, and `disabled`, and must return an `<li>`.

```tsx
<FileUpload
  multiple
  itemRender={(item) => (
    <li>
      {item.file.name}
      <button type="button" disabled={item.disabled} onClick={item.remove}>
        Remove
      </button>
    </li>
  )}
/>
```

### Rejections and form behavior

`accept`, `minSize`, `maxSize`, and `maxFiles` validate each picked or dropped file before it is
added. `maxFiles` counts files already selected and applies only with `multiple`. Rejected files are
reported to `onValueInvalid` as `rejections` with reason codes (`FILE_INVALID_TYPE`, `FILE_TOO_SMALL`, `FILE_TOO_LARGE`,
`FILE_DUPLICATE`, `TOO_MANY_FILES`); accepted files from the same batch are still added.

`readOnly` keeps the selected list visible but blocks adding and removing files. `disabled` removes
all interaction. Both inherit the enclosing Field's state when omitted, and an explicit `false`
overrides it.

```tsx
<FileUpload
  multiple
  accept="image/png,image/jpeg"
  maxFiles={2}
  maxSize={1024 * 1024}
  onValueInvalid={({ rejections }) => setRejections(rejections)}
/>
<FileUpload disabled label="Disabled upload" />
<FileUpload readOnly label="Read-only upload" />
```

### Keyboard interaction

| Key                                 | Description                                                                              |
| ----------------------------------- | ---------------------------------------------------------------------------------------- |
| <kbd>Enter</kbd> / <kbd>Space</kbd> | Opens the native operating system file picker dialog when the upload control is focused. |
| <kbd>Tab</kbd>                      | Navigates between the upload control and individual file removal buttons.                |

## Examples

### Attach expense receipts

Set `multiple` and `maxFiles` when the field holds a short list. Handle `onValueInvalid` when a fourth
file or a disallowed type is dropped.

```tsx
import { Badge, FileUpload } from 'moraine'
import type { FileUploadT } from 'moraine'
import { createSignal, For, Show } from 'solid-js'

export function MultipleMaxFiles() {
  type FileUploadValue = FileUploadT.Value

  const [receipts, setReceipts] = createSignal<FileUploadValue>([])
  const [rejectWarning, setRejectWarning] = createSignal<string | null>(null)

  const filesList = () => {
    const val = receipts()
    if (!val) {
      return []
    }
    return Array.isArray(val) ? val : [val]
  }

  return (
    <div class="p-4 b-1 b-border rounded-xl max-w-xl space-y-4">
      <div class="flex items-center justify-between">
        <div>
          <h4 class="text-sm font-medium">Expense receipts</h4>
          <p class="text-xs text-muted-foreground">
            Upload up to 3 receipt images or PDF documents.
          </p>
        </div>
        <Badge variant="outline">Max 3 files</Badge>
      </div>

      <FileUpload
        multiple
        maxFiles={3}
        accept="image/*,.pdf"
        label="Drop receipts here"
        description="PDF, PNG, JPG up to 10MB each"
        onValueChange={(val) => {
          setReceipts(val)
          setRejectWarning(null)
        }}
        onValueInvalid={({ rejections }) => {
          setRejectWarning(
            `Rejected ${rejections.length} file(s) exceeding the 3 file limit or invalid format.`,
          )
        }}
      />

      <Show when={rejectWarning()}>
        <p class="text-xs text-danger">{rejectWarning()}</p>
      </Show>

      <Show when={filesList().length > 0}>
        <div class="pt-2 border-t border-border space-y-2">
          <p class="text-xs text-muted-foreground font-medium">
            Attached files ({filesList().length}/3):
          </p>
          <div class="space-y-1">
            <For each={filesList()}>
              {(file) => (
                <div class="text-xs p-2 rounded-lg bg-muted/40 flex items-center justify-between">
                  <span class="font-medium truncate">{file.name}</span>
                  <span class="text-muted-foreground font-mono">
                    {(file.size / 1024).toFixed(1)} KB
                  </span>
                </div>
              )}
            </For>
          </div>
        </div>
      </Show>
    </div>
  )
}
```

### Show rejected images

Map `onValueInvalid` reason codes to messages. Validation runs before the file is added to the
value.

```tsx
import { FileUpload } from 'moraine'
import { For, createSignal } from 'solid-js'

const REJECTION_LABELS = {
  FILE_DUPLICATE: 'already selected',
  FILE_INVALID_TYPE: 'type is not accepted',
  FILE_TOO_LARGE: 'is larger than 1 MB',
  FILE_TOO_SMALL: 'is smaller than the minimum size',
  TOO_MANY_FILES: 'exceeds the file limit',
} as const

export function Rejections() {
  const [rejections, setRejections] = createSignal<{ name: string; reason: string }[]>([])

  return (
    <div class="max-w-lg space-y-3">
      <FileUpload
        multiple
        accept="image/png,image/jpeg"
        maxFiles={2}
        maxSize={1024 * 1024}
        label="Upload images"
        description="PNG or JPEG, up to 1 MB each (maximum two files)"
        onValueInvalid={({ rejections }) =>
          setRejections(
            rejections.map(({ file, errors }) => ({
              name: file.name,
              reason: errors.map((error) => REJECTION_LABELS[error]).join(', '),
            })),
          )
        }
      />

      <For each={rejections()}>
        {(rejection) => (
          <p class="text-sm text-danger">
            {rejection.name}: {rejection.reason}
          </p>
        )}
      </For>
    </div>
  )
}
```

### Attach from a compact button

Set `variant="button"` for a compact picker button instead of the drop area. The selected file still
comes from `onValueChange`.

```tsx
import { FileUpload } from 'moraine'
import type { FileUploadT } from 'moraine'
import { createSignal, Show } from 'solid-js'

export function ButtonVariant() {
  const [attached, setAttached] = createSignal<FileUploadT.Value>(null)

  const fileName = () => {
    const file = attached()
    if (!file) {
      return null
    }
    return Array.isArray(file) ? file[0]?.name : file.name
  }

  return (
    <div class="max-w-md space-y-3">
      <FileUpload
        variant="button"
        label="Attach files"
        description="Choose receipts or invoices from your computer."
        onValueChange={setAttached}
      />

      <Show when={fileName()}>
        <div class="text-xs text-muted-foreground px-3 py-2 rounded-lg bg-muted/40 flex gap-2 items-center">
          <span class="i-lucide:paperclip text-primary" />
          <span>Selected: {fileName()}</span>
        </div>
      </Show>
    </div>
  )
}
```

### Bind attachments to a form

Place FileUpload in `form.Field` so the schema owns required files and submit output.

```tsx
import { Button, createForm, FileUpload } from 'moraine'
import type { FileUploadT } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

export function FormIntegration() {
  const [formState, setFormState] = createSignal({
    attachment: null as File | null,
  })

  const updateFormAttachment = (value: FileUploadValue) => {
    const next = Array.isArray(value) ? (value[0] ?? null) : value
    setFormState((prev) => ({ ...prev, attachment: next }))
  }

  type FileUploadValue = FileUploadT.Value
  const form = createForm({
    schema: v.object({ attachment: v.file('Please upload one attachment.') }),
    initialInput: { attachment: undefined },
  })

  return (
    <form.Form>
      <div class="max-w-xl space-y-4">
        <form.Field
          name="attachment"
          label="Attachment"
          description="Upload at least one file before submit."
          required
        >
          <FileUpload id="demo-attachment-upload" onValueChange={updateFormAttachment} />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Validate
          </Button>
          <p class="text-xs text-muted-foreground">
            Current attachment: {formState().attachment?.name ?? 'none'}
          </p>
        </div>
      </div>
    </form.Form>
  )
}
```

### Freeze uploads during maintenance

`disabled` blocks new files. `readOnly` keeps the current list visible without allowing add or
remove.

```tsx
import { FileUpload } from 'moraine'

export function FormBehavior() {
  return (
    <div class="max-w-md w-full space-y-4">
      <FileUpload
        disabled
        label="Disabled upload"
        description="Upload is locked during maintenance."
      />
      <FileUpload
        readOnly
        label="Read-only upload"
        description="View existing attachments without making modifications."
      />
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-disabled` | `file-upload` | Present when the component, slot, or item is disabled. |
| `data-invalid` | `file-upload`, `file-upload-control` | Present when the field or form has a validation error. |
| `data-readonly` | `file-upload` | Present when the field is in read-only mode. |
| `data-required` | `file-upload` | Present when the field input is required. |
| `data-dragging` | `file-upload-control` | Present while the related thumb or handle is being dragged. |

### Props

Props for the FileUpload component.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| accept | string \| undefined | '*' | Comma-separated list of accepted file types. Each entry is a case-insensitive extension<br>(`.png`), a MIME wildcard (`image/*`), or an exact MIME type (`application/pdf`); `*`<br>accepts everything. It is also passed to the native file input and enforced on dropped<br>and picked files, which fail with `FILE_INVALID_TYPE` in `onValueInvalid`. |
| defaultValue | Value<TMultiple> \| undefined | — | Initial selection for uncontrolled usage. Defaults to `null` in single mode and `[]` when `multiple`. |
| description | JSX.Element \| undefined | — | Helper text inside the upload area, such as the accepted types. It is linked to the control through `aria-describedby`. |
| disabled | boolean \| undefined | false | Whether the control is disabled: it cannot be interacted with and sets `aria-disabled`.<br>When omitted, the control inherits `disabled` from the surrounding `Field`; an explicit<br>`false` overrides the `Field`. |
| dropzone | boolean \| undefined | true | Whether files can be dragged and dropped onto the control. When `false`, drag events are<br>ignored, but clicking the control or pressing `Enter` / `Space` still opens the file dialog. |
| fileIcon | IconT.Name \| undefined | 'icon-file' | Icon shown in a file entry when there is no image thumbnail, such as for non-image files. |
| fileList | boolean \| undefined | true | Whether to render the list of selected files below the control, with an object-URL<br>thumbnail for image files. When `false`, no list or previews are rendered and `itemRender`<br>is not used. |
| icon | IconT.Name \| undefined | 'icon-upload' | Icon shown in the upload area. |
| id | string \| undefined | — | The ID of the control's main focusable element, which a surrounding `Field` label points to<br>with `for`. A unique ID is generated when omitted. The control's related parts (hidden<br>input, label, description) derive their IDs from it, so keep it unique on the page. |
| inputRef | Ref<HTMLInputElement> \| undefined | — | Ref to the hidden native `<input type="file">` that backs the control. |
| itemRender | Component<ItemRenderProps> \| undefined | — | Replaces the default entry for each selected file in the file list. Receives the `file`,<br>its `index`, an image `previewUrl` when available, a `remove()` function, and `disabled`<br>(`true` while disabled or read-only). Render a list item (`<li>`), since entries sit in a `<ul>`. |
| label | JSX.Element \| undefined | — | Label text inside the upload area. It also names the control for assistive technology unless a surrounding `Field` supplies a label. |
| maxFiles | (TMultiple extends true ? number: never) \| undefined | — | Maximum total number of selected files, counting files already selected. Files beyond the<br>limit are dropped and reported as `TOO_MANY_FILES` in `onValueInvalid`. Only accepted when<br>`multiple` is `true`; single mode always keeps one file. Unlimited by default. |
| maxSize | number \| undefined | — | Maximum accepted file size in bytes, inclusive. Larger files are rejected with `FILE_TOO_LARGE`. |
| minSize | number \| undefined | — | Minimum accepted file size in bytes, inclusive. Smaller files are rejected with `FILE_TOO_SMALL`. |
| multiple | TMultiple \| undefined | false | Whether several files can be selected. When `true`, new files are appended to the current<br>selection and `value` is a `File[]`; otherwise a new file replaces the current one. |
| name | string \| undefined | — | The name of the control, used for native form submission. When omitted, the control uses<br>the name of its form binding or a string `name` set on the surrounding `Field`. |
| onValueChange | ((value: Value<TMultiple>) => void) \| undefined | — | Called when files are added or removed. Receives the complete new selection, a `File[]`<br>when `multiple` and `File \| null` otherwise (`null` once the file is removed). It is not<br>called for files rejected by validation or while the control is disabled or read-only. |
| onValueInvalid | ((details: ValueInvalidDetails) => void) \| undefined | — | Called after a pick or drop with the files that failed validation, each with its `errors`<br>codes: `FILE_INVALID_TYPE`, `FILE_TOO_SMALL`, `FILE_TOO_LARGE`, `FILE_DUPLICATE` (same<br>name, size, type, and modification time as a selected file), or `TOO_MANY_FILES`. Accepted<br>files from the same batch are still added and reported through `onValueChange`. It cannot<br>cancel the pick and is unrelated to the native `invalid` event. |
| readOnly | boolean \| undefined | false | Whether the control is read-only: the value is visible and focusable but cannot be changed,<br>and `aria-readonly` is set. When omitted, the control inherits `readOnly` from the<br>surrounding `Field`. |
| required | boolean \| undefined | false | Whether the control is required, which sets `aria-required` (and the native `required`<br>attribute where the control renders a native input). When omitted, the control inherits<br>`required` from the surrounding `Field`. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Visual size of the component. |
| translations | Translations \| undefined | — | Localized message overrides for this file upload instance. `label` is the accessible name<br>used when no visible `label` is set, and `remove` builds each remove button's `aria-label`<br>from the file `name`. |
| value | Value<TMultiple> \| undefined | — | The selected file(s) (controlled): `File \| null` in single mode, `File[]` when `multiple`.<br>`undefined` leaves the selection uncontrolled; pass `null` (single) or `[]` (multiple) for a<br>controlled empty selection. Update it from `onValueChange`. |
| variant | 'area' \| 'button' \| undefined | 'area' | Visual treatment of the control: a large dashed drop area, or a compact picker button. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`itemRender` example**

```tsx
import { FileUpload } from 'moraine'

<FileUpload
  multiple
  itemRender={(item) => (
    <li>
      {item.file.name}
      <button type="button" disabled={item.disabled} onClick={item.remove}>
        Remove
      </button>
    </li>
  )}
/>
```

**`onValueInvalid` example**

```tsx
import { FileUpload } from 'moraine'

<FileUpload
  maxSize={2 * 1024 * 1024}
  onValueInvalid={({ rejections }) => {
    for (const { file, errors } of rejections) {
      console.warn(file.name, errors.includes('FILE_TOO_LARGE') ? 'is over 2 MB' : errors)
    }
  }}
/>
```

**`translations` example**

```tsx
import { FileUpload } from 'moraine'

<FileUpload
  label="Avatar"
  translations={{ label: 'Upload avatar', remove: ({ name }) => `Delete ${name}` }}
/>
```
