---
title: "FileUpload"
description: "Компонент загрузки файлов."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/file-upload"
---
# FileUpload

> Компонент загрузки файлов.

## Использование

Директива `v-model` управляет значением FileUpload.

Модель принимает нативные объекты [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) или собственные объекты [`FileUploadItem`](#with-custom-file-items) со свойствами:

- `name: string`
- `size?: number`
- `type?: string`
- `avatar?: AvatarProps`

Тип элемента по умолчанию `File`; при собственных элементах он выводится из модели. `FileUploadItem` можно расширить своими свойствами.

```vue
<script setup lang="ts">
const value = ref(null)
</script>

<template>
  <B24FileUpload v-model="value" class="w-96 min-h-48" />
</template>
```

### Несколько файлов

Пропс `multiple` разрешает выбрать несколько файлов.

```vue
<template>
  <B24FileUpload multiple class="w-96 min-h-48" />
</template>
```

### Зона перетаскивания

Пропс `dropzone` включает и отключает область для перетаскивания. По умолчанию `true`.

```vue
<template>
  <B24FileUpload :dropzone="false" class="w-96 min-h-48" />
</template>
```

### Интерактивность

Пропс `interactive` включает и отключает область, по которой можно щёлкнуть. По умолчанию `true`.

> [!TIP]
> See: #with-files-bottom-slot
> Пригодится, если в слот `#actions` добавлен компонент `Button`.

```vue
<template>
  <B24FileUpload :interactive="false" class="w-96 min-h-48" />
</template>
```

### Допустимые типы

Пропс `accept` задаёт допустимые типы файлов. Передайте список [MIME-типов](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types) или расширений через запятую (например, `image/png,application/pdf,.jpg`). По умолчанию `*` (любые файлы).

```vue
<template>
  <B24FileUpload accept="image/*" class="w-96 min-h-48" />
</template>
```

### Подпись

Пропс `label` задаёт подпись FileUpload.

```vue
<template>
  <B24FileUpload label="Перетащите изображение сюда" class="w-96 min-h-48" />
</template>
```

### Описание

Пропс `description` задаёт описание FileUpload.

```vue
<template>
  <B24FileUpload label="Перетащите изображение сюда" description="SVG, PNG, JPG или GIF (не больше 2 МБ)" class="w-96 min-h-48" />
</template>
```

### Иконка

Пропс `icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) FileUpload.

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
</script>

<template>
  <B24FileUpload :icon="RocketIcon" label="Перетащите изображение сюда" description="SVG, PNG, JPG или GIF (не больше 2 МБ)" class="w-96 min-h-48" />
</template>
```

### Цвет

Пропс `color` меняет цвет FileUpload.

```vue
<template>
  <B24FileUpload color="air-primary-alert" highlight label="Перетащите изображение сюда" description="SVG, PNG, JPG или GIF (не больше 2 МБ)" class="w-96 min-h-48" />
</template>
```

> [!NOTE]
> Пропс `highlight` здесь показывает состояние фокуса. Внутри компонента он включается при ошибке валидации.

### Вариант

Пропс `variant` меняет вариант FileUpload.

```vue
<template>
  <B24FileUpload variant="button" />
</template>
```

### Размер

Пропс `size` меняет размер FileUpload.

```vue
<template>
  <B24FileUpload size="lg" variant="area" label="Перетащите изображение сюда" description="SVG, PNG, JPG или GIF (не больше 2 МБ)" />
</template>
```

### Раскладка

Пропс `layout` меняет способ отображения файлов в FileUpload. По умолчанию `grid`.

> [!WARNING]
> Пропс работает только при `variant` равном `area`.

```vue
<template>
  <B24FileUpload layout="list" multiple label="Перетащите изображения сюда" description="SVG, PNG, JPG или GIF (не больше 2 МБ)" class="w-96" :b24ui="{base:'min-h-48'}" />
</template>
```

### Положение

Пропс `position` меняет положение файлов в FileUpload. По умолчанию `outside`.

> [!WARNING]
> Пропс работает только при `variant` равном `area` и `layout` равном `list`.

```vue
<template>
  <B24FileUpload position="inside" layout="list" multiple label="Перетащите изображения сюда" description="SVG, PNG, JPG или GIF (не больше 2 МБ)" class="w-96" :b24ui="{base:'min-h-48'}" />
</template>
```

## Примеры

### С собственными элементами-файлами `2.15+`

Чтобы показать уже существующий файл, передайте объект с `name`, необязательными метаданными файла и [Avatar](https://b24-ui.bx-shef.by/raw/docs/components/avatar.md). Нативные файлы, выбранные пользователем, попадают в ту же модель. В моделях и слотах файлов рядом с вашим типом есть `File`, поэтому перед обращением к собственным свойствам сузьте тип элемента.

```vue [FileUploadItemsExample.vue]
<script setup lang="ts">
import type { FileUploadItem } from '@bxshefby/b24ui-nuxt'

const files = ref<FileUploadItem[]>([{
  name: 'bitrix24.png',
  size: 1000,
  type: 'image/png',
  avatar: {
    src: 'https://github.com/bitrix24.png',
    alt: 'Bitrix24'
  }
}])
</script>

<template>
  <B24FileUpload
    v-model="files"
    layout="list"
    label="Перетащите изображения сюда"
    description="SVG, PNG, JPG или GIF"
    accept="image/*"
    multiple
    class="w-96 min-h-48"
  />
</template>
```

### Со статусом загрузки `2.15+`

Расширьте `FileUploadItem` своими полями и показывайте в слотах файлов прогресс загрузки и другие асинхронные состояния. В примере выбранные файлы превращаются в собственные элементы, имитируется прогресс загрузки, а по завершении показываются превью изображений.

```vue [FileUploadStatusExample.vue]
<script setup lang="ts">
import type { FileUploadItem } from '@bxshefby/b24ui-nuxt'
import LoaderWaitIcon from '@bitrix24/b24icons-vue/animated/LoaderWaitIcon'
import CircleCheckIcon from '@bitrix24/b24icons-vue/outline/CircleCheckIcon'
import CrossMIcon from '@bitrix24/b24icons-vue/outline/CrossMIcon'
import { useIntervalFn } from '@vueuse/core'

interface UploadFileItem extends FileUploadItem {
  progress: number
  preview: string
}

const uploadingAvatar = {
  icon: LoaderWaitIcon
}
const files = ref<UploadFileItem[]>([{
  name: 'bitrix24.png',
  size: 1000,
  type: 'image/png',
  progress: 0,
  preview: 'https://github.com/bitrix24.png',
  avatar: uploadingAvatar
}])
const objectUrls = new Set<string>()

function onUpdateFiles(value: (File | UploadFileItem)[] | null | undefined) {
  files.value = (value || []).map((file) => {
    if (!(file instanceof File)) return file

    const preview = URL.createObjectURL(file)
    objectUrls.add(preview)

    return {
      name: file.name,
      size: file.size,
      type: file.type,
      progress: 0,
      preview,
      avatar: uploadingAvatar
    }
  })

  for (const url of objectUrls) {
    if (files.value.some(file => file.preview === url)) continue
    URL.revokeObjectURL(url)
    objectUrls.delete(url)
  }
}

useIntervalFn(() => {
  for (const file of files.value) {
    if (file.progress === 100) continue

    file.progress = Math.min(file.progress + 2, 100)
    if (file.progress === 100) {
      file.avatar = { src: file.preview, alt: file.name }
    }
  }
}, 100)

onScopeDispose(() => {
  for (const url of objectUrls) URL.revokeObjectURL(url)
})
</script>

<template>
  <B24FileUpload
    :model-value="files"
    layout="list"
    label="Перетащите изображения сюда"
    description="SVG, PNG, JPG или GIF"
    accept="image/*"
    multiple
    class="w-96 min-h-48"
    @update:model-value="onUpdateFiles"
  >
    <template #file-trailing="{ file, index, removeFile }">
      <div class="ms-auto flex items-center gap-2">
        <B24Progress
          v-if="'progress' in file && file.progress < 100"
          :model-value="file.progress"
          size="xs"
          class="w-20"
        />
        <CircleCheckIcon
          v-else-if="'progress' in file && file.progress === 100"
          class="size-5 text-(--ui-color-accent-main-success)"
        />
        <B24Button
          color="air-tertiary-no-accent"
          size="xs"
          :icon="CrossMIcon"
          :aria-label="`Удалить ${file.name}`"
          @click.stop.prevent="removeFile(index)"
        />
      </div>
    </template>
  </B24FileUpload>
</template>
```

### С валидацией формы

FileUpload можно использовать вместе с компонентами [Form](https://b24-ui.bx-shef.by/raw/docs/components/form.md) и [FormField](https://b24-ui.bx-shef.by/raw/docs/components/form-field.md), чтобы обрабатывать валидацию и ошибки.

```vue [FileUploadFormValidationExample.vue]
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const MAX_FILE_SIZE = 2 * 1024 * 1024 // 2MB
const MIN_DIMENSIONS = { width: 200, height: 200 }
const MAX_DIMENSIONS = { width: 4096, height: 4096 }
const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']

const formatBytes = (bytes: number, decimals = 2) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ', 'ПБ', 'ЭБ', 'ЗБ', 'ЙБ']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

const schema = z.object({
  image: z
    .instanceof(File, {
      message: 'Выберите файл изображения.'
    })
    .refine(file => file.size <= MAX_FILE_SIZE, {
      message: `Изображение слишком большое. Выберите изображение меньше ${formatBytes(MAX_FILE_SIZE)}.`
    })
    .refine(file => ACCEPTED_IMAGE_TYPES.includes(file.type), {
      message: 'Загрузите корректный файл изображения (JPEG, PNG или WebP).'
    })
    .refine(
      file =>
        new Promise((resolve) => {
          const reader = new FileReader()
          reader.onload = (e) => {
            const img = new Image()
            img.onload = () => {
              const meetsDimensions
                = img.width >= MIN_DIMENSIONS.width
                  && img.height >= MIN_DIMENSIONS.height
                  && img.width <= MAX_DIMENSIONS.width
                  && img.height <= MAX_DIMENSIONS.height
              resolve(meetsDimensions)
            }
            img.src = e.target?.result as string
          }
          reader.readAsDataURL(file)
        }),
      {
        message: `Недопустимые размеры изображения. Загрузите изображение от ${MIN_DIMENSIONS.width}x${MIN_DIMENSIONS.height} до ${MAX_DIMENSIONS.width}x${MAX_DIMENSIONS.height} пикселей.`
      }
    )
})

type Schema = z.output<typeof schema>

const state = reactive<Partial<Schema>>({
  image: undefined
})

async function onSubmit(event: FormSubmitEvent<Schema>) {
  console.log(event.data)
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4 w-96" @submit="onSubmit">
    <B24FormField name="image" label="Изображение" description="JPG, GIF или PNG. Не более 2 МБ.">
      <B24FileUpload v-model="state.image" accept="image/*" class="min-h-48" />
    </B24FormField>

    <B24Button type="submit" label="Отправить" />
  </B24Form>
</template>
```

### С отклонёнными файлами `2.15+`

Файлы, не подходящие под `accept`, при перетаскивании игнорируются. Чтобы показать сообщение об ошибке, подпишитесь на событие `reject`.

```vue [FileUploadRejectExample.vue]
<script setup lang="ts">
import ImageIcon from '@bitrix24/b24icons-vue/outline/ImageIcon'

const value = ref<File[]>([])

const toast = useToast()

function onReject(files: File[]) {
  toast.add({
    title: 'Допускаются только изображения',
    description: files.map(file => file.name).join(', '),
    color: 'air-primary-alert'
  })
}
</script>

<template>
  <B24FileUpload
    v-model="value"
    accept="image/*"
    :icon="ImageIcon"
    label="Перетащите изображения сюда"
    description="SVG, PNG, JPG или GIF"
    multiple
    class="w-96 min-h-48"
    @reject="onReject"
  />
</template>
```

### Со слотом по умолчанию

Слот по умолчанию позволяет собрать собственный компонент загрузки.

> [!NOTE]
> Если нужен только выбор файлов без обёртки, воспользуйтесь композаблом `useFileUpload`: на нём построен сам FileUpload. `const { open, isDragging, inputRef, dropzoneRef } = useFileUpload({ accept: 'image/*', multiple: true, onUpdate: files => {} })`. `open()` открывает диалог выбора файлов, `dropzoneRef` привязывается к элементу, принимающему перетаскивание, а `isDragging` показывает состояние наведения. Разметка остаётся за вами: композабл ничего не отрисовывает.

> [!WARNING]
> `inputRef` нужен, только если в DOM требуется настоящий `<input type="file">` — для нативной отправки формы или валидации. Он ожидает **компонент**, а не элемент: значение читается как `inputRef.value.$el`, и FileUpload привязывает его к `VisuallyHidden as="input"`. Если привязать его к обычному `<input>`, ничего не произойдёт: `$el` не определён, и перетащенные файлы не попадут в поле. Если поле не нужно, оставьте `inputRef` непривязанным.

> [!WARNING]
> `accept` попадает в диалог выбора как есть, а зона перетаскивания получает только MIME-часть: при перетаскивании известен тип, но не имя файла. Поэтому если `accept` состоит только из расширений (`'.pdf,.docx'`), зона перетаскивания примет любые файлы. Когда важны именно расширения, проверяйте имя в `onUpdate`.

```vue [FileUploadDefaultSlotExample.vue]
<script setup lang="ts">
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'
import * as z from 'zod'
import ImageIcon from '@bitrix24/b24icons-vue/outline/ImageIcon'

const MAX_FILE_SIZE = 2 * 1024 * 1024 // 2MB
const MIN_DIMENSIONS = { width: 200, height: 200 }
const MAX_DIMENSIONS = { width: 4096, height: 4096 }
const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']

const formatBytes = (bytes: number, decimals = 2) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ', 'ПБ', 'ЭБ', 'ЗБ', 'ЙБ']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

const schema = z.object({
  avatar: z
    .instanceof(File, {
      message: 'Выберите файл изображения.'
    })
    .refine(file => file.size <= MAX_FILE_SIZE, {
      message: `Изображение слишком большое. Выберите изображение меньше ${formatBytes(MAX_FILE_SIZE)}.`
    })
    .refine(file => ACCEPTED_IMAGE_TYPES.includes(file.type), {
      message: 'Загрузите корректный файл изображения (JPEG, PNG или WebP).'
    })
    .refine(
      file =>
        new Promise((resolve) => {
          const reader = new FileReader()
          reader.onload = (e) => {
            const img = new Image()
            img.onload = () => {
              const meetsDimensions
                = img.width >= MIN_DIMENSIONS.width
                  && img.height >= MIN_DIMENSIONS.height
                  && img.width <= MAX_DIMENSIONS.width
                  && img.height <= MAX_DIMENSIONS.height
              resolve(meetsDimensions)
            }
            img.src = e.target?.result as string
          }
          reader.readAsDataURL(file)
        }),
      {
        message: `Недопустимые размеры изображения. Загрузите изображение от ${MIN_DIMENSIONS.width}x${MIN_DIMENSIONS.height} до ${MAX_DIMENSIONS.width}x${MAX_DIMENSIONS.height} пикселей.`
      }
    )
})

type Schema = z.output<typeof schema>

const state = reactive<Partial<Schema>>({
  avatar: undefined
})

function createObjectUrl(file: File): string {
  return URL.createObjectURL(file)
}

async function onSubmit(event: FormSubmitEvent<Schema>) {
  console.log(event.data)
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4 w-64" @submit="onSubmit">
    <B24FormField name="avatar" label="Аватар" description="JPG, GIF или PNG. Не более 1 МБ.">
      <B24FileUpload v-slot="{ open, removeFile }" v-model="state.avatar" accept="image/*">
        <div class="flex flex-wrap items-center gap-3">
          <B24Avatar size="lg" :src="state.avatar ? createObjectUrl(state.avatar) : undefined" :icon="ImageIcon" />

          <B24Button :label="state.avatar ? 'Изменить изображение' : 'Загрузить изображение'" color="air-selection" @click="open()" />
        </div>

        <p v-if="state.avatar" class="text-(length:--ui-font-size-xs) text-description mt-1.5">
          {{ state.avatar.name }}

          <B24Button
            label="Удалить"
            color="air-primary-alert"
            size="xs"
            class="p-0"
            @click="removeFile()"
          />
        </p>
      </B24FileUpload>
    </B24FormField>

    <B24Button type="submit" label="Отправить" />
  </B24Form>
</template>
```

### Со слотом files-bottom

Слот `files-bottom` позволяет добавить [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md) под списком файлов, например, чтобы удалить все файлы.

```vue [FileUploadFilesBottomSlotExample.vue]
<script setup lang="ts">
import ImageIcon from '@bitrix24/b24icons-vue/outline/ImageIcon'
import UploadIcon from '@bitrix24/b24icons-vue/outline/UploadIcon'

const value = ref<File[]>([])
</script>

<template>
  <B24FileUpload
    v-model="value"
    :icon="ImageIcon"
    label="Перетащите изображения сюда"
    description="SVG, PNG, JPG или GIF (не более 2 МБ)"
    layout="list"
    multiple
    :interactive="false"
    class="w-96 min-h-48"
  >
    <template #actions="{ open }">
      <B24Button
        label="Выберите изображения"
        :icon="UploadIcon"
        color="air-selection"
        @click="open()"
      />
    </template>

    <template #files-bottom="{ removeFile, files }">
      <B24Button
        v-if="files?.length"
        label="Удалить все файлы"
        color="air-primary-alert"
        @click="removeFile()"
      />
    </template>
  </B24FileUpload>
</template>
```

> [!NOTE]
> See: #interactive
> В этом примере пропс `interactive` равен `false`, чтобы отключить область, по которой можно щёлкнуть.

### Со слотом files-top

Слот `files-top` позволяет добавить [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md) над списком файлов, например, чтобы добавить новые файлы.

```vue [FileUploadFilesTopSlotExample.vue]
<script setup lang="ts">
import ImageIcon from '@bitrix24/b24icons-vue/outline/ImageIcon'
import UploadIcon from '@bitrix24/b24icons-vue/outline/UploadIcon'

const value = ref<File[]>([])
</script>

<template>
  <B24FileUpload
    v-model="value"
    :icon="ImageIcon"
    label="Перетащите изображения сюда"
    description="SVG, PNG, JPG или GIF (не более 2 МБ)"
    layout="grid"
    multiple
    :interactive="false"
    class="w-96 min-h-48"
  >
    <template #actions="{ open }">
      <B24Button
        label="Выберите изображения"
        :icon="UploadIcon"
        color="air-selection"
        @click="open()"
      />
    </template>

    <template #files-top="{ open, files }">
      <div v-if="files?.length" class="mb-2 flex items-center justify-between">
        <p class="font-(--ui-font-weight-bold)">
          Files ({{ files?.length }})
        </p>

        <B24Button
          label="Добавить ещё"
          color="air-selection"
          class="-my-2"
          @click="open()"
        />
      </div>
    </template>
  </B24FileUpload>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the FileUpload component
 */
interface FileUploadProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  id?: string | undefined;
  name?: string | undefined;
  /**
   * The icon to display. Set to `false` to hide the icon.
   * @default icons.upload
   */
  icon?: false | (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  label?: string | undefined;
  description?: string | undefined;
  /**
   * @default 'air-tertiary'
   */
  color?: "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-warning" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-tertiary";
  /**
   * The `button` variant is only available when `multiple` is `false`.
   * @default 'area'
   */
  variant?: "button" | "area" | undefined;
  /**
   * @default 'md'
   */
  size?: "xs" | "sm" | "md" | "lg" | undefined;
  /**
   * The layout of how files are displayed.
   * Only works when `variant` is `area`.
   * @default 'grid'
   */
  layout?: "list" | "grid" | undefined;
  /**
   * The position of the files.
   * Only works when `variant` is `area` and when `layout` is `list`.
   * @default 'outside'
   */
  position?: "inside" | "outside" | undefined;
  /**
   * Highlight the ring color like a focus state.
   */
  highlight?: boolean | undefined;
  /**
   * Specifies the allowed file types for the input. Provide a comma-separated list of MIME types or file extensions (e.g., "image/png,application/pdf,.jpg").
   * @default '*'
   */
  accept?: string | undefined;
  modelValue?: null | (M extends true ? T[] : T) & (M extends true ? (T | File)[] : T | File) | undefined;
  /**
   * @default false
   */
  multiple?: M | undefined;
  /**
   * Reset the file input when the dialog is opened.
   * @default false
   */
  reset?: boolean | undefined;
  /**
   * Create a zone that allows the user to drop files onto it.
   * @default true
   */
  dropzone?: boolean | undefined;
  /**
   * Make the dropzone interactive when the user is clicking on it.
   * @default true
   */
  interactive?: boolean | undefined;
  required?: boolean | undefined;
  disabled?: boolean | undefined;
  /**
   * The icon to display for the file.
   * @default icons.file
   */
  fileIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * Preview the file (currently only `<img>` is rendered)
   * When set false, only `fileIcon` is displayed
   * @default true
   */
  fileImage?: boolean | undefined;
  /**
   * Configure the delete button for the file.
   * When `layout` is `grid`, the default is `{ color: 'air-secondary-no-accent', size: 'xs' }`
   * When `layout` is `list`, the default is `{ color: 'air-tertiary-no-accent' }`
   * @default true
   */
  fileDelete?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed to delete a file.
   * @default icons.close
   */
  fileDeleteIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * Show the file preview/list after upload.
   * @default true
   */
  preview?: boolean | undefined;
  b24ui?: { root?: SlotClass; base?: SlotClass; wrapper?: SlotClass; icon?: SlotClass; avatar?: SlotClass; label?: SlotClass; description?: SlotClass; actions?: SlotClass; files?: SlotClass; file?: SlotClass; fileLeadingAvatar?: SlotClass; fileWrapper?: SlotClass; fileName?: SlotClass; fileSize?: SlotClass; fileTrailingButton?: SlotClass; } | undefined;
  form?: string | undefined;
  formaction?: string | undefined;
  formenctype?: string | undefined;
  formmethod?: string | undefined;
  formnovalidate?: false | true | "true" | "false" | undefined;
  formtarget?: string | undefined;
}
```

> [!NOTE]
> See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes
> Компонент поддерживает и все нативные HTML-атрибуты `<input>`.

### Слоты

```ts
/**
 * Slots for the FileUpload component
 */
interface FileUploadSlots {
  default(): any;
  leading(): any;
  label(): any;
  description(): any;
  actions(): any;
  files(): any;
  files-top(): any;
  files-bottom(): any;
  file(): any;
  file-leading(): any;
  file-name(): any;
  file-size(): any;
  file-trailing(): any;
}
```

### События

```ts
/**
 * Emitted events for the FileUpload component
 */
interface FileUploadEmits {
  change: (payload: [event: Event]) => void;
  reject: (payload: [files: File[]]) => void;
  update:modelValue: (payload: [value: FileUploadFiles<T | File, M> | undefined]) => void;
}
```

### Доступ через ref

При обращении к компоненту через ref в шаблоне доступно:

| Имя | Тип |
| --- | --- |
| `inputRef` | `Ref<HTMLInputElement \| null>` |
| `dropzoneRef` | `Ref<HTMLDivElement \| null>` |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    fileUpload: {
      slots: {
        root: 'relative flex flex-col',
        base: 'w-full flex-1 bg-(--b24ui-background)/90 border-(--b24ui-border-color) border-(length:--b24ui-border-width) text-(--b24ui-color) flex flex-col gap-2 items-stretch justify-center rounded-(--ui-border-radius-md) focus-visible:outline-2 transition-[background]',
        wrapper: 'flex flex-col items-center justify-center text-center',
        icon: 'shrink-0',
        avatar: 'shrink-0',
        label: 'mt-2 text-(--b24ui-color) font-(--ui-font-weight-medium)',
        description: 'mt-1 text-description',
        actions: 'mt-4 flex flex-wrap gap-1.5 shrink-0',
        files: '',
        file: 'relative',
        fileLeadingAvatar: 'shrink-0',
        fileWrapper: 'flex flex-col min-w-0',
        fileName: 'text-(--b24ui-color) truncate',
        fileSize: 'text-description truncate',
        fileTrailingButton: ''
      },
      variants: {
        color: {
          'air-primary': {
            root: 'light style-filled-inverted'
          },
          'air-primary-success': {
            root: 'light style-filled-success-inverted'
          },
          'air-primary-alert': {
            root: 'light style-filled-alert-inverted'
          },
          'air-primary-copilot': {
            root: 'light style-filled-copilot-inverted'
          },
          'air-primary-warning': {
            root: 'light style-filled-warning-inverted'
          },
          'air-secondary': {
            root: 'style-outline'
          },
          'air-secondary-alert': {
            root: 'light style-tinted-alert'
          },
          'air-secondary-accent': {
            root: 'light style-tinted'
          },
          'air-secondary-accent-1': {
            root: 'style-outline-accent-1'
          },
          'air-secondary-accent-2': {
            root: 'style-outline-accent-2'
          },
          'air-tertiary': {
            root: 'style-outline-no-accent'
          }
        },
        variant: {
          area: {
            wrapper: 'px-4 py-3',
            base: 'p-4'
          },
          button: {}
        },
        size: {
          xs: {
            base: 'text-(length:--ui-font-size-xs)',
            icon: 'size-4',
            file: 'text-(length:--ui-font-size-xs) px-2 py-1 gap-1',
            fileWrapper: 'flex-row gap-1'
          },
          sm: {
            base: 'text-(length:--ui-font-size-xs)',
            icon: 'size-4',
            file: 'text-(length:--ui-font-size-xs) px-2.5 py-1.5 gap-1.5',
            fileWrapper: 'flex-row gap-1'
          },
          md: {
            base: 'text-(length:--ui-font-size-sm)',
            icon: 'size-5',
            file: 'text-(length:--ui-font-size-xs) px-2.5 py-1.5 gap-1.5'
          },
          lg: {
            base: 'text-(length:--ui-font-size-sm)',
            icon: 'size-5',
            file: 'text-(length:--ui-font-size-sm) px-3 py-2 gap-2',
            fileSize: 'text-(length:--ui-font-size-xs)'
          }
        },
        layout: {
          list: {
            root: 'gap-2 items-start',
            files: 'flex flex-col w-full gap-2',
            file: 'min-w-0 w-full rounded-(--ui-border-radius-md) flex items-center border border-(--b24ui-border-color)',
            fileTrailingButton: 'ms-auto'
          },
          grid: {
            fileWrapper: 'hidden',
            fileLeadingAvatar: 'size-full rounded-lg',
            fileTrailingButton: 'absolute -top-1.5 -end-1.5 rounded-(--ui-border-radius-pill) border edge-light:[--ui-btn-background:var(--ui-color-base-white-fixed)] edge-dark:[--ui-btn-background:var(--ui-color-base-white-fixed)] edge-dark:hover:bg-(--ui-color-base-white-fixed)/90 edge-dark:[--ui-btn-color:var(--ui-color-g-content-grey-1)] dark:[--ui-btn-background:var(--ui-color-g-content-grey-1)] dark:hover:bg-(--ui-color-g-content-grey-1)/90 dark:[--ui-btn-color:var(--ui-color-g-content-grey-4)]'
          }
        },
        position: {
          inside: '',
          outside: ''
        },
        dropzone: {
          true: 'border-dashed data-[dragging=true]:bg-(--ui-color-accent-soft-grey-1)/90'
        },
        interactive: {
          true: ''
        },
        highlight: {
          true: ''
        },
        multiple: {
          true: ''
        },
        disabled: {
          true: 'cursor-not-allowed opacity-75'
        }
      },
      compoundVariants: [
        {
          class: 'focus-visible:outline-(--ui-color-design-outline-focused-stroke)'
        },
        {
          highlight: true,
          class: {
            base: 'ring-1 ring-inset ring-(--b24ui-border-color)'
          }
        },
        {
          size: 'xs',
          layout: 'list',
          class: {
            fileTrailingButton: '-me-1'
          }
        },
        {
          size: 'sm',
          layout: 'list',
          class: {
            fileTrailingButton: '-me-1.5'
          }
        },
        {
          size: 'md',
          layout: 'list',
          class: {
            fileTrailingButton: '-me-1.5'
          }
        },
        {
          size: 'lg',
          layout: 'list',
          class: {
            fileTrailingButton: '-me-2'
          }
        },
        {
          variant: 'button',
          size: 'xs',
          class: {
            base: 'p-1'
          }
        },
        {
          variant: 'button',
          size: 'sm',
          class: {
            base: 'p-1.5'
          }
        },
        {
          variant: 'button',
          size: 'md',
          class: {
            base: 'p-1.5'
          }
        },
        {
          variant: 'button',
          size: 'lg',
          class: {
            base: 'p-2'
          }
        },
        {
          layout: 'grid',
          multiple: true,
          class: {
            files: 'grid grid-cols-2 md:grid-cols-3 gap-4 w-full',
            file: 'p-0 aspect-square'
          }
        },
        {
          layout: 'grid',
          multiple: false,
          class: {
            file: 'absolute inset-0 p-0'
          }
        },
        {
          interactive: true,
          disabled: false,
          class: 'hover:bg-elevated/25'
        }
      ],
      defaultVariants: {
        color: 'air-tertiary',
        variant: 'area',
        size: 'md'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
