---
title: "ChatAttachment"
description: "Показывает файл, прикреплённый к запросу или сообщению чата, с превью и состоянием загрузки."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/chat-attachment"
---
# ChatAttachment

> Показывает файл, прикреплённый к запросу или сообщению чата, с превью и состоянием загрузки.

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

Компонент ChatAttachment показывает файл: имя, описание и рядом с ними превью картинки или иконку.

> [!NOTE]
> Компонент [`ChatPrompt`](https://b24-ui.bx-shef.by/raw/docs/components/chat-prompt.md#files) сам использует его для списка файлов, привязанных через `v-model:files`.

### Файл

Пропс `file` принимает `File`, например выбранный пользователем. Имя, тип и размер берутся из него, а превью картинки строится через object URL.

```vue
<script setup lang="ts">
defineProps<{
  file: File
}>()
</script>

<template>
  <B24ChatAttachment :file="file" />
</template>
```

### Имя

Пропсы `name` и `type` описывают файл, о котором известны только сведения, например файловую часть сообщения.

```vue
<template>
  <B24ChatAttachment name="quarterly-report.pdf" type="application/pdf" />
</template>
```

### Адрес

Пропс `url` задаёт адрес картинки для превью. Картинка выводится, если `type` — тип изображения, а `name` служит её альтернативным текстом.

```vue
<template>
  <B24ChatAttachment name="landscape.jpg" type="image/jpeg" url="https://picsum.photos/id/1015/200" />
</template>
```

> [!TIP]
> Файловую часть сообщения сопоставляют с этими пропсами в слоте `#files` компонентов [ChatMessage](https://b24-ui.bx-shef.by/raw/docs/components/chat-message.md) и [ChatMessages](https://b24-ui.bx-shef.by/raw/docs/components/chat-messages.md).
> ```vue
> <template>
>   <B24ChatMessages :messages="messages" :status="status">
>     <template #files="{ parts }">
>       <B24ChatAttachment
>         v-for="(part, index) in parts"
>         :key="index"
>         :name="part.filename"
>         :type="part.mediaType"
>         :url="part.url"
>       />
>     </template>
>   </B24ChatMessages>
> </template>
> ```

### Описание

Пропс `description` задаёт текст под именем. По умолчанию это расширение файла и, если передан `file`, его размер.

```vue
<template>
  <B24ChatAttachment description="Загружен 2 минуты назад" name="quarterly-report.pdf" type="application/pdf" />
</template>
```

### Статус

Пропс `status` показывает, что файл загружается (`uploading`) или загрузка не удалась (`error`). По умолчанию `idle`.

> [!NOTE]
> Пока файл загружается, имя переливается, картинка тускнеет, а иконка файла сменяется индикатором загрузки. Ход загрузки или, при `error`, причину сбоя передавайте в пропс `description`.

```vue
<template>
  <B24ChatAttachment status="uploading" name="quarterly-report.pdf" type="application/pdf" />
</template>
```

### Ориентация

Пропс `orientation` меняет раскладку вложения. По умолчанию `horizontal`, а `vertical` даёт картинке крупное превью.

```vue
<template>
  <B24ChatAttachment orientation="vertical" name="landscape.jpg" type="image/jpeg" url="https://picsum.photos/id/1015/200" />
</template>
```

### Вариант

Пропс `variant` меняет оформление вложения. По умолчанию `card`, а `thumbnail` показывает только картинку или иконку файла: кнопка удаления сидит на её углу, а имя остаётся доступным для программ экранного доступа. Вместе с пропсом `size` получается превью от `40px` для `xs` до `120px` для `xl`.

```vue
<template>
  <B24ChatAttachment variant="thumbnail" name="landscape.jpg" type="image/jpeg" url="https://picsum.photos/id/1015/200" removable />
</template>
```

> [!NOTE]
> Пропс `orientation` действует только для варианта `card`.

### Размер

Пропс `size` задаёт размер вложения. По умолчанию `md`.

```vue
<template>
  <B24ChatAttachment size="sm" name="quarterly-report.pdf" type="application/pdf" />
</template>
```

### Удаление

Пропс `removable` выводит кнопку, которая вызывает событие `remove`.

```vue
<template>
  <B24ChatAttachment removable name="quarterly-report.pdf" type="application/pdf" />
</template>
```

### Иконка

Пропс `icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) для файлов, которые не картинки. По умолчанию `icons.file`.

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

<template>
  <B24ChatAttachment :icon="RocketIcon" name="quarterly-report.pdf" type="application/pdf" />
</template>
```

Иконки состояний и кнопки удаления настраиваются пропсами `loadingIcon`, `errorIcon` и `removeIcon`.

## API

### Пропсы

```ts
/**
 * Props for the ChatAttachment component
 */
interface ChatAttachmentProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  /**
   * The file to display, its `name`, `type` and size are read from it and images are previewed.
   */
  file?: File | undefined;
  /**
   * The name of the file.
   */
  name?: string | undefined;
  /**
   * The media type of the file, images are previewed.
   */
  type?: string | undefined;
  /**
   * The URL of the file, used to preview images.
   */
  url?: string | undefined;
  /**
   * The text displayed under the name. Defaults to the file extension and size.
   */
  description?: string | undefined;
  /**
   * The upload status of the file.
   * @default 'idle'
   */
  status?: "error" | "idle" | "uploading" | undefined;
  /**
   * @default 'md'
   */
  size?: "sm" | "md" | "lg" | "xs" | "xl" | undefined;
  /**
   * The orientation of the attachment, `vertical` gives an image a large preview.
   * @default 'horizontal'
   */
  orientation?: "horizontal" | "vertical" | undefined;
  /**
   * The style of the attachment, `thumbnail` only shows the preview with the remove button on its corner.
   * @default 'card'
   */
  variant?: "card" | "thumbnail" | undefined;
  /**
   * Display a button to remove the file.
   * @default false
   */
  removable?: boolean | undefined;
  /**
   * The icon displayed for files that are not images.
   * @default icons.file
   */
  icon?: (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;
  /**
   * The icon displayed while the file uploads, over the image if any.
   * @default icons.loading
   */
  loadingIcon?: (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;
  /**
   * The icon displayed when the upload fails, over the image if any.
   * @default icons.caution
   */
  errorIcon?: (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;
  /**
   * The icon of the remove button.
   * @default icons.close
   */
  removeIcon?: (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;
  b24ui?: { root?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; image?: SlotClass; wrapper?: SlotClass; name?: SlotClass; description?: SlotClass; remove?: SlotClass; } | undefined;
}
```

### События

```ts
/**
 * Emitted events for the ChatAttachment component
 */
interface ChatAttachmentEmits {
  remove: (payload: [event: MouseEvent]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    chatAttachment: {
      slots: {
        root: 'group/attachment relative flex min-w-0 max-w-full w-fit shrink-0',
        leading: 'relative flex items-center justify-center shrink-0 aspect-square overflow-hidden rounded-(--ui-border-radius-md) bg-(--ui-color-bg-content-secondary) text-(--ui-color-design-plain-na-content-secondary)',
        leadingIcon: 'absolute shrink-0',
        image: 'size-full object-cover',
        wrapper: 'grid grid-cols-[minmax(0,1fr)_auto] items-center min-w-0 flex-1',
        name: 'block truncate font-(--ui-font-weight-medium) text-(--ui-color-design-plain-content)',
        description: 'block truncate row-start-2 text-(length:--ui-font-size-xs) text-description',
        remove: 'shrink-0'
      },
      variants: {
        size: {
          xs: {
            root: 'gap-1.5 p-1 rounded-(--ui-border-radius-md) text-(length:--ui-font-size-xs) data-[orientation=vertical]:w-20 data-[variant=thumbnail]:w-10',
            leading: 'w-7 rounded-(--ui-border-radius-sm)',
            leadingIcon: 'size-3.5',
            description: 'text-[10px]/3'
          },
          sm: {
            root: 'gap-2 p-1.5 text-(length:--ui-font-size-xs) data-[orientation=vertical]:w-24 data-[variant=thumbnail]:w-12',
            leading: 'w-8',
            leadingIcon: 'size-4'
          },
          md: {
            root: 'gap-2.5 p-2 text-(length:--ui-font-size-sm) data-[orientation=vertical]:w-30 data-[variant=thumbnail]:w-14',
            leading: 'w-10',
            leadingIcon: 'size-5',
            description: 'mt-0.5'
          },
          lg: {
            root: 'gap-3 p-2.5 text-(length:--ui-font-size-sm) data-[orientation=vertical]:w-36 data-[variant=thumbnail]:w-20',
            leading: 'w-12',
            leadingIcon: 'size-6',
            description: 'mt-0.5'
          },
          xl: {
            root: 'gap-3 p-3 text-(length:--ui-font-size-md) data-[orientation=vertical]:w-44 data-[variant=thumbnail]:w-30',
            leading: 'w-14 rounded-(--ui-border-radius-lg)',
            leadingIcon: 'size-7',
            description: 'mt-0.5 text-(length:--ui-font-size-sm)'
          }
        },
        orientation: {
          horizontal: {
            root: 'items-center min-w-40 pe-2.5',
            remove: 'col-start-2 row-start-1 -my-1 ms-1'
          },
          vertical: {
            root: 'flex-col',
            leading: 'w-full',
            leadingIcon: 'size-6',
            wrapper: 'px-1',
            remove: 'absolute top-3 end-3 rounded-(--ui-border-radius-pill) bg-(--ui-color-bg-content-primary)/75 backdrop-blur-xs'
          }
        },
        variant: {
          card: {
            root: 'rounded-(--ui-border-radius-lg) border border-(--ui-color-divider-default) bg-(--ui-color-bg-content-primary)'
          },
          thumbnail: {
            root: 'p-0 min-w-0',
            leading: 'w-full outline -outline-offset-1 outline-(--ui-color-divider-default)',
            wrapper: 'contents',
            name: 'sr-only',
            description: 'sr-only',
            remove: 'absolute -top-1.5 -end-1.5 m-0 p-0 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)] [@media(hover:hover)]:opacity-0 group-hover/attachment:opacity-100 group-focus-within/attachment:opacity-100 transition-opacity ease-out'
          }
        },
        status: {
          idle: '',
          uploading: {
            leading: 'has-data-[slot=image]:text-(--ui-color-design-plain-content)',
            image: 'opacity-50'
          },
          error: {
            root: 'border-(--ui-color-accent-main-alert)/30',
            leading: 'bg-(--ui-color-accent-main-alert)/10 text-(--ui-color-accent-main-alert) outline-(--ui-color-accent-main-alert)/30',
            image: 'opacity-50',
            description: 'text-(--ui-color-accent-main-alert)'
          }
        }
      },
      defaultVariants: {
        size: 'md',
        orientation: 'horizontal',
        status: 'idle',
        variant: 'card'
      }
    }
  }
})
```

## Sitemap

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