# File Drop

> A drop area that receives local files by drag and drop or the file picker.

```tsx title="hero.tsx"
import type { FileDropRejection } from '@langgenius/dify-ui/file-drop'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import * as React from 'react'

type SelectedFile = {
  id: number
  file: File
}

const maxFiles = 5
const maxFileSize = 15 * 1024 * 1024

const sizeFormat = new Intl.NumberFormat('en', {
  notation: 'compact',
  style: 'unit',
  unit: 'byte',
  unitDisplay: 'narrow',
})

const rejectionLabels: Record<FileDropRejection['reason'], string> = {
  type: 'unsupported type',
  count: `over the ${maxFiles}-file limit`,
}

export function FileDropHeroDemo() {
  const [files, setFiles] = React.useState<SelectedFile[]>([])
  const [skipped, setSkipped] = React.useState<{ event: Event; messages: string[] }>()
  const nextIdRef = React.useRef(0)

  const reportSkipped = (event: Event, messages: string[]) =>
    setSkipped((current) =>
      current?.event === event
        ? { event, messages: [...current.messages, ...messages] }
        : { event, messages },
    )

  return (
    <div className="flex w-full max-w-md flex-col gap-3">
      <FileDrop
        accept=".pdf,.md,.txt,.docx"
        multiple
        maxFiles={maxFiles - files.length}
        onFilesSelect={(accepted, { event }) => {
          const valid = accepted
            .filter((file) => file.size <= maxFileSize)
            .map((file) => ({ id: ++nextIdRef.current, file }))
          setFiles((current) => [...current, ...valid])
          reportSkipped(
            event,
            accepted
              .filter((file) => file.size > maxFileSize)
              .map((file) => `${file.name} (over 15 MB)`),
          )
        }}
        onFilesReject={(rejections, { event }) =>
          reportSkipped(
            event,
            rejections.map(({ file, reason }) => `${file.name} (${rejectionLabels[reason]})`),
          )
        }
        render={<section aria-label="Knowledge base upload" />}
        className="flex flex-col items-center gap-1 rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-5 py-6 text-center transition-colors data-dragging:border-components-dropzone-border-accent data-dragging:bg-components-dropzone-bg-accent"
      >
        <span aria-hidden="true" className="i-ri-upload-cloud-2-line size-6 text-text-tertiary" />
        <p className="system-sm-regular text-text-secondary">
          Drag documents here, or{' '}
          <FileDropTrigger className="rounded-sm system-sm-medium text-text-accent hover:underline active:opacity-80">
            browse
          </FileDropTrigger>
        </p>
        <p className="system-xs-regular text-text-tertiary">
          PDF, Markdown, TXT or DOCX. Up to 5 files, 15 MB each.
        </p>
      </FileDrop>
      {skipped && skipped.messages.length > 0 && (
        <p role="alert" className="system-xs-regular text-text-destructive">
          Skipped {skipped.messages.join(', ')}
        </p>
      )}
      {files.length > 0 && (
        <ul aria-label="Selected documents" className="flex flex-col gap-1">
          {files.map(({ id, file }) => (
            <li
              key={id}
              className="flex items-center gap-2 rounded-lg border border-components-panel-border bg-components-panel-bg py-1 ps-3 pe-1"
            >
              <span
                aria-hidden="true"
                className="i-ri-file-text-line size-4 shrink-0 text-text-tertiary"
              />
              <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">
                {file.name}
              </span>
              <span className="shrink-0 system-xs-regular text-text-tertiary tabular-nums">
                {sizeFormat.format(file.size)}
              </span>
              <IconButton
                aria-label={`Remove ${file.name}`}
                size="md"
                className="active:bg-state-base-active"
                onClick={() => {
                  setFiles((current) => current.filter((item) => item.id !== id))
                  setSkipped(undefined)
                }}
              >
                <span aria-hidden="true" className="i-ri-close-line size-4" />
              </IconButton>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
```

## Usage guidelines

- **Always include a `FileDropTrigger`**: Dragging needs a pointer. The trigger is the keyboard and screen reader path: it is a button that opens the system file picker, while the hidden file input stays out of the tab order.
- **Name the area and the trigger**: Render the root as a landmark with a name, such as `render={<section aria-label="Knowledge base upload" />}`, and give the trigger visible text that says what it does.
- **Pick one selection mode**: Without `multiple`, `onFileSelect` receives exactly one file and a selection of several files is rejected as a whole. With `multiple`, `onFilesSelect` receives the accepted files and `maxFiles` keeps the first ones.
- **Report every rejection**: `accept` filters both dropped and picked files. Files that fail it arrive in `onFilesReject` with reason `type`; files over the limit arrive with reason `count`. Show the message in a `role="alert"` element next to the area. With `multiple`, a mixed drop calls `onFilesSelect` first and `onFilesReject` after it, with the same `eventDetails.event`, so one message can cover the whole selection.
- **Check file size yourself**: `FileDrop` checks type and count only. State the accepted types and the size limit in visible text, filter oversized files in `onFilesSelect`, and report them with the other rejections. To cap the total across several selections, pass the remaining slots as `maxFiles`.
- **Keep the files in feature state**: `FileDrop` is not a form control. It does not register with `Field` or `Form`, and its input has no `name`. Store the selected files and send them when the form submits, and validate a missing file in the submit handler.
- **Style the drop state with data attributes**: The root has no surface styles. Use `data-dragging` for the drag highlight and `data-disabled` for the unavailable state; the trigger receives the same attributes.
- **Use `disabled` when uploads are unavailable**: The area refuses drops and the trigger becomes a disabled button. Explain why in nearby text.
- **Folders need `expandDirectories`**: Dropped folders are skipped by default. Set `expandDirectories` to replace each folder with the files inside it, recursively; the same `accept` and count rules apply to the result.

## Anatomy

```tsx
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
```

```tsx
<FileDrop>
  <FileDropTrigger />
</FileDrop>
```

`FileDrop` renders a `<div>` with a hidden `<input type="file">` inside it. `accept` and `multiple` configure both that input and the drop validation. A drag that carries no files, such as selected text, passes through untouched.

## Examples

### Single file and rejection feedback

Without `multiple`, the area accepts one file. Once a file is chosen, a second `FileDropTrigger` rendered as a `Button` replaces it.

```tsx title="single-file.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
import * as React from 'react'

export function FileDropSingleFileDemo() {
  const [file, setFile] = React.useState<File | null>(null)
  const [error, setError] = React.useState<string | null>(null)

  return (
    <div className="flex w-full max-w-md flex-col gap-2">
      <FileDrop
        accept=".csv"
        onFileSelect={(selected) => {
          setFile(selected)
          setError(null)
        }}
        onFilesReject={(rejections) => {
          setError(
            rejections.some(({ reason }) => reason === 'count')
              ? 'Drop one CSV file at a time.'
              : 'Annotations import only accepts .csv files.',
          )
        }}
        render={<section aria-label="Annotation CSV upload" />}
        className="flex min-h-20 items-center gap-3 rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-5 py-4 transition-colors data-dragging:border-components-dropzone-border-accent data-dragging:bg-components-dropzone-bg-accent"
      >
        <span
          aria-hidden="true"
          className="i-ri-file-excel-2-line size-6 shrink-0 text-text-tertiary"
        />
        {file ? (
          <React.Fragment>
            <span className="min-w-0 flex-1 truncate system-sm-medium text-text-secondary">
              {file.name}
            </span>
            <FileDropTrigger render={<Button size="small" className="shrink-0" />}>
              Replace file
            </FileDropTrigger>
          </React.Fragment>
        ) : (
          <p className="flex-1 system-sm-regular text-text-tertiary">
            Drag a CSV of question and answer pairs here, or{' '}
            <FileDropTrigger className="rounded-sm system-sm-medium text-text-accent hover:underline active:opacity-80">
              browse
            </FileDropTrigger>
          </p>
        )}
      </FileDrop>
      {error && (
        <p role="alert" className="system-xs-regular text-text-destructive">
          {error}
        </p>
      )}
    </div>
  )
}
```

### Inside a form

Keep the chosen file in state and check for it when the form submits. The submit button stays enabled; submitting without a file shows the error and links it to the trigger with `aria-describedby`. While the package installs, the submit button shows `loading`, repeated submits are ignored and the area is disabled. A rejected package reports in the same error message, and success is announced in a status region.

```tsx title="form.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
import * as React from 'react'

export function FileDropFormDemo() {
  const [file, setFile] = React.useState<File | null>(null)
  const [error, setError] = React.useState<string | null>(null)
  const [status, setStatus] = React.useState<'idle' | 'installing' | 'installed'>('idle')
  const errorId = React.useId()
  const timerRef = React.useRef<number | null>(null)

  React.useEffect(() => {
    return () => {
      if (timerRef.current !== null) window.clearTimeout(timerRef.current)
    }
  }, [])

  function install(selected: File) {
    setStatus('installing')
    setError(null)
    timerRef.current = window.setTimeout(() => {
      timerRef.current = null
      if (selected.size === 0) {
        setError(`${selected.name} is empty or damaged.`)
        setStatus('idle')
        return
      }
      setStatus('installed')
    }, 1000)
  }

  return (
    <form
      aria-label="Install plugin"
      className="flex w-full max-w-md flex-col gap-3"
      onSubmit={(event) => {
        event.preventDefault()
        if (status === 'installing') return
        if (!file) {
          setError('Choose a .difypkg file to install.')
          return
        }
        install(file)
      }}
    >
      <FileDrop
        accept=".difypkg"
        disabled={status === 'installing'}
        onFileSelect={(selected) => {
          setFile(selected)
          setError(null)
          setStatus('idle')
        }}
        onFilesReject={() => setError('Plugins are installed from a single .difypkg file.')}
        render={<section aria-label="Plugin package upload" />}
        className="flex flex-col items-center gap-2 rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-5 py-6 text-center transition-colors data-disabled:cursor-not-allowed data-disabled:border-divider-regular data-disabled:bg-background-section data-dragging:border-components-dropzone-border-accent data-dragging:bg-components-dropzone-bg-accent"
      >
        <p className="w-full truncate system-sm-regular text-text-secondary">
          {file ? file.name : 'Drop a .difypkg plugin package here'}
        </p>
        <FileDropTrigger
          render={<Button size="small" />}
          aria-describedby={error ? errorId : undefined}
        >
          {file ? 'Choose another package' : 'Choose package'}
        </FileDropTrigger>
      </FileDrop>
      {error && (
        <p id={errorId} role="alert" className="system-xs-regular text-text-destructive">
          {error}
        </p>
      )}
      <div className="flex items-center justify-between gap-3">
        <span role="status" className="min-w-0 truncate system-xs-regular text-text-success">
          {status === 'installed' && file ? `Installed ${file.name}` : ''}
        </span>
        <Button
          type="submit"
          variant="primary"
          loading={status === 'installing'}
          className="shrink-0"
        >
          Install plugin
        </Button>
      </div>
    </form>
  )
}
```

### Disabled

A disabled area ignores drops and disables its trigger. The surrounding text says why uploads are unavailable.

```tsx title="disabled.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'

export function FileDropDisabledDemo() {
  return (
    <FileDrop
      accept=".pdf,.md,.txt"
      multiple
      disabled
      onFilesSelect={() => {}}
      render={<section aria-label="Sandbox document upload" />}
      className="flex w-full max-w-md flex-col items-center gap-2 rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-5 py-6 text-center data-disabled:cursor-not-allowed data-disabled:border-divider-regular data-disabled:bg-background-section"
    >
      <span aria-hidden="true" className="i-ri-upload-cloud-2-line size-6 text-text-disabled" />
      <div className="flex flex-col gap-0.5">
        <p className="system-sm-medium text-text-secondary">
          Document limit reached for the Sandbox plan
        </p>
        <p className="system-xs-regular text-text-tertiary">Upgrade to upload more documents.</p>
      </div>
      <FileDropTrigger render={<Button size="small" />}>Choose files</FileDropTrigger>
    </FileDrop>
  )
}
```

## Keyboard

| Key              | Action                                                               |
| ---------------- | -------------------------------------------------------------------- |
| `Tab`            | Moves focus to the trigger. The hidden file input is not a tab stop. |
| `Enter`, `Space` | Opens the system file picker from the trigger.                       |

## API reference

### FileDrop

Receives local files via drag-and-drop or the system file picker, letting non-file drags pass through untouched. Renders a `<div>` element.

Exposes `data-dragging` and `data-disabled` without imposing surface styles; validates `accept` and file counts unless `validate={false}`.

**Props**

| Prop                 | Type                                                                            | Default | Description                                                                                                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accept?`            | `string`                                                                        | —       | Configures the native file picker and, unless `validate={false}`, filters selected files using `<input accept>` syntax.                                                                             |
| `disabled?`          | `boolean`                                                                       | `false` | Whether the component should ignore drops and file picker activation.                                                                                                                               |
| `expandDirectories?` | `boolean`                                                                       | —       | Replaces each dropped folder with the files inside it, recursively.                                                                                                                                 |
| `multiple?`          | `boolean`                                                                       | `false` | Whether more than one file can be selected.                                                                                                                                                         |
| `maxFiles?`          | `number`                                                                        | —       | Type-accepted files past this limit are rejected with `count`, keeping the first ones.                                                                                                              |
| `validate?`          | `boolean`                                                                       | `true`  | Whether selected files are filtered by `accept` and file count. When `false`, every dropped or picked file goes to `onFilesSelect`; `accept` and `multiple` still configure the native file picker. |
| `onFileSelect?`      | `((file: File, eventDetails: FileDropEventDetails) => void)`                    | —       | Receives exactly one file. Any multi-file selection is rejected as a whole with `count`.                                                                                                            |
| `onFilesSelect?`     | `(files: File[], eventDetails: FileDropEventDetails) => void`                   | —       | Receives the accepted files.                                                                                                                                                                        |
| `onFilesReject?`     | `(rejections: FileDropRejection[], eventDetails: FileDropEventDetails) => void` | —       | Receives the files rejected by `accept` or the file count.                                                                                                                                          |

Valid prop combinations:

- `multiple: boolean`, `maxFiles?: number`, `validate?: true`, `onFileSelect?: undefined`, `onFilesSelect: (files: File[], eventDetails: FileDropEventDetails) => void`, `onFilesReject?: ((rejections: FileDropRejection[], eventDetails: FileDropEventDetails) => void)`
- `multiple?: false`, `maxFiles?: undefined`, `validate?: true`, `onFileSelect: (file: File, eventDetails: FileDropEventDetails) => void`, `onFilesSelect?: undefined`, `onFilesReject?: ((rejections: FileDropRejection[], eventDetails: FileDropEventDetails) => void)`
- `multiple?: boolean`, `maxFiles?: undefined`, `validate: false`, `onFileSelect?: undefined`, `onFilesSelect: (files: File[], eventDetails: FileDropEventDetails) => void`, `onFilesReject?: undefined`

Inherits `className`, `render`, `style` from [Base UI null](https://base-ui.com/react/handbook/composition).

**Data attributes**

| Attribute       | Description                                               |
| --------------- | --------------------------------------------------------- |
| `data-dragging` | Present while files are being dragged over the drop area. |
| `data-disabled` | Present when the drop area is disabled.                   |

### FileDropTrigger

Opens the system file picker as the keyboard and screen-reader path to the drop area. Renders a `<button>` element.

Inherits `nativeButton`, `className`, `render`, `style` from [Base UI null](https://base-ui.com/react/handbook/composition).

**Data attributes**

| Attribute       | Description                                               |
| --------------- | --------------------------------------------------------- |
| `data-dragging` | Present while files are being dragged over the drop area. |
| `data-disabled` | Present when the drop area is disabled.                   |
