# File Upload

> Drops or picks files, then lists them with their size and upload progress.

A file upload takes files by drag and drop or from the file picker, then lists each file with its size, its progress and any error, such as a master audio file.

## When to use

- Use it when a form needs a file: a master, a cover letter, a contract.
- Write the allowed types and the size limit in the hint: "WAV atau FLAC, maks. 200 MB."
- The client only narrows the picker with `accept`. The backend checks what is inside the file, and its message shows under that file.
- On phones there is nothing to drag: the area works as a button that opens the picker.

_Live preview of the React and Vue versions: https://design.sosialoka.tech/components/file-upload/_

## Anatomy

1. Drop zone, also a button
2. Upload icon
3. File row
4. Upload progress

| Part | Style |
| --- | --- |
| Drop area | `rounded-lg`, a dashed `input` border, `bg-muted/30`, 24px padding, centered. On hover and while dragging, `border-primary` and `bg-primary-soft`. |
| Text | "Tarik file ke sini atau pilih file", then the hint in `text-xs muted-foreground`. |
| File row | One row per file on `card` with a `border`: name, size, a [Progress](https://design.sosialoka.tech/components/progress/) bar while it uploads, and a remove button. |
| Error | The backend's message under the file in `destructive`; the row border turns `destructive`. |

## Props

| React | Vue | Flutter | Type | Default | Use |
| --- | --- | --- | --- | --- | --- |
| `accept` | `accept` | `file_picker` `allowedExtensions` | text | any | Narrows the picker, such as `.wav,.flac`. |
| `multiple` | `multiple` | `allowMultiple` | boolean | `false` | Lets people add several files. |
| `files`, `onFilesChange` | `v-model:files` | your list | `{ file, progress?, error? }[]` | `[]` | The files, with progress (0–100) and the backend's error. |
| `onRemove` | `@remove` | your handler | function | none | Runs after a file is removed, for example to cancel its upload. |
| `hint`, `error` | `hint`, `error` | `Text` | text | none | The limits, and a backend message about the whole upload. |
| `label`, `buttonLabel` | `label`, `button-label` | `Text` | text | English | The area's text: `label` from `sm` up, `buttonLabel` on phones, such as "Pilih file". |
| `removeLabel`, `uploadingLabel` | same | `Semantics` | function | English | Names the buttons and bars, such as "Hapus master.wav". |
| `locale` | `locale` | `NumberFormat` locale | text | `en-GB` | How file sizes read, such as `"id-ID"` for `4,1 MB`. |

Flutter has no upload widget; the snippet draws the area from the theme, and products open the picker with the `file_picker` package.

## Code

**React**
```tsx
import { useEffect, useState } from "react"
import { FileUpload, type FileUploadItem } from "@/components/ui/file-upload"

/** A file the backend already turned down, so the demo shows the error state. */
const rejected = new File(["demo"], "demo-lama.mp3", { type: "audio/mpeg" })
Object.defineProperty(rejected, "size", { value: 4_300_000 })

export default function FileUploadDemo() {
  const [files, setFiles] = useState<FileUploadItem[]>([{ file: rejected, error: "Format file-nya belum pas." }])

  // Pretend to upload: new files fill their progress bar, then settle.
  useEffect(() => {
    if (!files.some((f) => f.progress !== undefined)) return
    const timer = setTimeout(
      () =>
        setFiles((list) =>
          list.map((f) => (f.progress === undefined ? f : f.progress >= 100 ? { file: f.file } : { ...f, progress: f.progress + 25 }))
        ),
      400
    )
    return () => clearTimeout(timer)
  }, [files])

  return (
    <FileUpload
      className="max-w-md"
      accept=".wav,.flac"
      multiple
      label="Tarik file ke sini atau pilih file"
      buttonLabel="Pilih file"
      locale="id-ID"
      hint="WAV atau FLAC, maks. 200 MB."
      removeLabel={(name) => `Hapus ${name}`}
      uploadingLabel={(name) => `Mengunggah ${name}`}
      files={files}
      onFilesChange={(next) => setFiles(next.map((f) => (files.includes(f) ? f : { file: f.file, progress: 0 })))}
    />
  )
}
```

**Vue**
```vue
<script setup lang="ts">
import type { FileUploadItem } from "@/components/ui/file-upload"
import { onBeforeUnmount, ref, watch } from "vue"
import { FileUpload } from "@/components/ui/file-upload"

/** A file the backend already turned down, so the demo shows the error state. */
const rejected = new File(["demo"], "demo-lama.mp3", { type: "audio/mpeg" })
Object.defineProperty(rejected, "size", { value: 4_300_000 })

const files = ref<FileUploadItem[]>([{ file: rejected, error: "Format file-nya belum pas." }])

/** New files start uploading. */
function update(next: FileUploadItem[]) {
  files.value = next.map(f => (files.value.includes(f) ? f : { file: f.file, progress: 0 }))
}

// Pretend to upload: new files fill their progress bar, then settle.
let timer: ReturnType<typeof setTimeout> | undefined
watch(files, (list) => {
  clearTimeout(timer)
  if (!list.some(f => f.progress !== undefined)) return
  timer = setTimeout(() => {
    files.value = files.value.map(f => (f.progress === undefined ? f : f.progress >= 100 ? { file: f.file } : { ...f, progress: f.progress + 25 }))
  }, 400)
})
onBeforeUnmount(() => clearTimeout(timer))
</script>

<template>
  <FileUpload
    class="max-w-md"
    accept=".wav,.flac"
    multiple
    label="Tarik file ke sini atau pilih file"
    button-label="Pilih file"
    locale="id-ID"
    hint="WAV atau FLAC, maks. 200 MB."
    :remove-label="(name) => `Hapus ${name}`"
    :uploading-label="(name) => `Mengunggah ${name}`"
    :files="files"
    @update:files="update"
  />
</template>
```

**Flutter**
```dart
// shadcn_ui has no upload widget: a card with an input-colored border, a "Pilih file" button and the file list.
// In a product, open the system picker with the file_picker package (not installed in this example).
// Error text per file comes from the backend.
import 'package:flutter/widgets.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:sosialoka_ui/sosialoka_ui.dart';

class FileUploadDemo extends StatelessWidget {
  const FileUploadDemo({super.key});

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final c = context.sosialoka;
    return ConstrainedBox(
      constraints: const BoxConstraints(maxWidth: 448),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              border: Border.all(color: theme.colorScheme.input),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              children: [
                Icon(LucideIcons.upload, color: theme.colorScheme.mutedForeground),
                const SizedBox(height: 8),
                // Phones have nothing to drag from: the area only offers the picker.
                const Text('Pilih file dari perangkatmu.'),
                const SizedBox(height: 4),
                Text('WAV atau FLAC, maks. 200 MB.', style: theme.textTheme.muted),
                const SizedBox(height: 12),
                ShadButton.outline(onPressed: () {}, child: const Text('Pilih file')),
              ],
            ),
          ),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              border: Border.all(color: c.destructive),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                Icon(LucideIcons.fileAudio, size: 16, color: theme.colorScheme.mutedForeground),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text('demo-lama.mp3 · 4,3 MB'),
                      Text('Format file-nya belum pas.', style: theme.textTheme.small.copyWith(color: c.destructive)),
                    ],
                  ),
                ),
                Semantics(
                  label: 'Hapus demo-lama.mp3',
                  child: ShadIconButton.ghost(icon: const Icon(LucideIcons.x, size: 16), onPressed: () {}),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
```

## Install

**React**
```bash
npx shadcn@latest add https://design.sosialoka.tech/r/react/file-upload.json
```

**Vue**
```bash
npx shadcn-vue@latest add https://design.sosialoka.tech/r/vue/file-upload.json
```

## Accessibility

- The drop area is a button: Enter and Space open the file picker.
- The hint and the backend's error about the whole upload are linked to the area with `aria-describedby`.
- Each remove button is named after its file, such as "Hapus master.wav", and a file's error is linked to it.
- Each progress bar is named, such as "Mengunggah master.wav".
