# File Upload

> Menarik atau memilih file, lalu menampilkannya dengan ukuran dan progres unggahnya.

File Upload menerima file lewat tarik-lepas atau pemilih file, lalu menampilkan setiap file dengan ukuran, progres, dan error-nya, misalnya file master audio.

## Kapan dipakai

- Pakai saat form butuh file: master, surat pengantar, kontrak.
- Tulis jenis file dan batas ukuran di hint: "WAV atau FLAC, maks. 200 MB."
- Klien hanya membatasi pemilih file dengan `accept`. Backend yang memeriksa isi file, dan pesannya tampil di bawah file itu.
- Di HP tidak ada yang bisa ditarik: area ini menjadi tombol yang membuka pemilih file.

_Pratinjau langsung versi React dan Vue: https://design.sosialoka.tech/id/components/file-upload/_

## Anatomi

1. Area taruh file, sekaligus tombol
2. Ikon unggah
3. Baris file
4. Progres unggahan

| Bagian | Gaya |
| --- | --- |
| Area unggah | `rounded-lg`, border putus-putus `input`, `bg-muted/30`, padding 24px, rata tengah. Saat hover dan saat file ditarik ke atasnya: `border-primary` dan `bg-primary-soft`. |
| Teks | "Tarik file ke sini atau pilih file", lalu hint dengan `text-xs muted-foreground`. |
| Baris file | Satu baris per file di `card` dengan `border`: nama, ukuran, bar [Progress](https://design.sosialoka.tech/id/components/progress/) saat mengunggah, dan tombol hapus. |
| Error | Pesan dari backend di bawah file dengan warna `destructive`; border barisnya ikut `destructive`. |

## Props

| React | Vue | Flutter | Tipe | Bawaan | Kegunaan |
| --- | --- | --- | --- | --- | --- |
| `accept` | `accept` | `allowedExtensions` di `file_picker` | teks | semua | Membatasi pemilih file, misalnya `.wav,.flac`. |
| `multiple` | `multiple` | `allowMultiple` | boolean | `false` | Mengizinkan beberapa file. |
| `files`, `onFilesChange` | `v-model:files` | daftarmu sendiri | `{ file, progress?, error? }[]` | `[]` | Daftar file, dengan progres (0–100) dan error dari backend. |
| `onRemove` | `@remove` | handler-mu | fungsi | tidak ada | Dijalankan setelah file dihapus, misalnya untuk membatalkan unggahannya. |
| `hint`, `error` | `hint`, `error` | `Text` | teks | tidak ada | Batasannya, dan pesan backend tentang unggahan secara keseluruhan. |
| `label`, `buttonLabel` | `label`, `button-label` | `Text` | teks | bahasa Inggris | Teks area: `label` mulai `sm`, `buttonLabel` di HP, misalnya "Pilih file". |
| `removeLabel`, `uploadingLabel` | sama | `Semantics` | fungsi | bahasa Inggris | Nama tombol dan bar, misalnya "Hapus master.wav". |
| `locale` | `locale` | locale `NumberFormat` | teks | `en-GB` | Cara ukuran file ditulis, misalnya `"id-ID"` untuk `4,1 MB`. |

Flutter tidak punya widget unggah; snippet-nya menggambar area dari tema, dan produk membuka pemilih file dengan paket `file_picker`.

## Kode

**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: () {}),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
```

## Instal

**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
```

## Aksesibilitas

- Area unggah adalah tombol: Enter dan Spasi membuka pemilih file.
- Hint dan error backend tentang unggahan secara keseluruhan terhubung ke area itu lewat `aria-describedby`.
- Setiap tombol hapus dinamai sesuai file-nya, misalnya "Hapus master.wav", dan error sebuah file terhubung ke tombol itu.
- Setiap bar progres diberi nama, misalnya "Mengunggah master.wav".
