Skip to main content

FileUpload

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

Props
Slots

Anatomy#

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.

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.

<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>.

<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.

<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
↵ / Space Opens the native operating system file picker dialog when the upload control is focused.
⇥ 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.

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.

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.

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.

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.

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

Props#

Props for the FileUpload component. Renders a <div> element by default.

Prop