---
title: "Upload and Download"
description: "File upload and download with progress tracking."
canonical_url: "https://nuxt.mhaibaraai.cn/en/docs/api/upload-download"
---
# Upload and Download

> File upload and download with progress tracking.

## useUploadWithProgress

### Usage

`useUploadWithProgress` plugs an XHR adapter in as the underlying fetch of the same `$api` pipeline (the fetch spec still cannot report upload progress in mainstream browsers), so endpoint headers, auth, business validation, Toast, error normalization and `movk:api:*` hooks match `useApiFetch` exactly. The returned `data` is unwrapped per the endpoint policy and every failure is an `ApiError`.

```vue
<script setup lang="ts">
const selected = ref<File[] | null>(null)
const { progress, status, data, error, upload, abort } = useUploadWithProgress<{
  files: Array<{ name: string, size: number }>
}>()

async function handleUpload() {
  const { data, error: err, aborted } = await upload('/api/upload', selected.value!, {
    fieldName: 'files',
    onSuccess: d => console.log('Upload succeeded:', d.files)
  })

  if (aborted) return
  if (err) console.error(err)
  else console.log(data?.files)
}
</script>

<template>
  <UFileUpload v-model="selected" multiple />
  <UButton :disabled="!selected?.length" @click="handleUpload">Upload</UButton>
  <UProgress v-if="status === 'pending'" :model-value="progress ?? undefined" :max="100" />
  <UButton v-if="status === 'pending'" @click="abort">Cancel</UButton>
</template>
```

> [!NOTE]
> 
> Use this for scenarios that require displaying upload progress. For small files where progress is not needed, you can use 
> 
> $api
> 
>  directly.

### Basic Multi-File Upload

`fieldName` determines the FormData field name (defaults to `'file'`); `upload()` returns `{ data, error, aborted }`:

```vue [ComposablesUseUploadProgressBasicExample.vue]
<script setup lang="ts">
const STATUS = {
  idle: { color: 'neutral', label: '空闲' },
  pending: { color: 'info', label: '上传中' },
  success: { color: 'success', label: '完成' },
  error: { color: 'error', label: '失败' },
  aborted: { color: 'warning', label: '已取消' }
} as const

const selected = ref<File[] | null>(null)
const basic = useUploadWithProgress<{ files: Array<{ name: string, size: number }> }>()
</script>

<template>
  <div class="flex flex-col gap-3">
    <UFileUpload v-model="selected" multiple label="拖拽或点击选择文件" />
    <div class="flex items-center gap-2">
      <UButton
        :loading="basic.status.value === 'pending'"
        :disabled="!selected?.length"
        icon="i-lucide-upload"
        @click="basic.upload('/upload', selected!, { fieldName: 'files' })"
      >
        开始上传
      </UButton>
      <UButton
        v-if="basic.status.value === 'pending'"
        color="error"
        variant="soft"
        icon="i-lucide-x"
        @click="basic.abort"
      >
        中止
      </UButton>
      <UBadge :color="STATUS[basic.status.value].color" variant="subtle">
        {{ basic.progress.value ?? 0 }}% · {{ STATUS[basic.status.value].label }}
      </UBadge>
    </div>
    <UProgress :model-value="basic.progress.value ?? undefined" :max="100" />
    <UAlert
      v-if="basic.error.value"
      color="error"
      variant="subtle"
      :description="basic.error.value.message"
    />
    <UCard v-if="basic.data.value">
      <pre class="text-xs overflow-auto">{{ basic.data.value }}</pre>
    </UCard>
  </div>
</template>
```

### Single File, Multiple Files and Extra Fields

Pass a `File` for single-file upload or a `File[]` for multiple files (appended under the same `fieldName`); `fields` injects extra form fields submitted alongside the file:

```ts
await upload('/api/upload', file, { fieldName: 'file' })
await upload('/api/upload', [f1, f2, f3], { fieldName: 'files' })

await upload('/api/upload', file, {
  fieldName: 'avatar',
  fields: { userId: '123', visibility: 'private' }
})
```

```vue [ComposablesUseUploadProgressSingleExample.vue]
<script setup lang="ts">
const STATUS = {
  idle: { color: 'neutral', label: '空闲' },
  pending: { color: 'info', label: '上传中' },
  success: { color: 'success', label: '完成' },
  error: { color: 'error', label: '失败' },
  aborted: { color: 'warning', label: '已取消' }
} as const

const selected = ref<File | null>(null)
const single = useUploadWithProgress()
</script>

<template>
  <div class="flex flex-col gap-3">
    <UFileUpload v-model="selected" label="选择单个文件" />
    <div class="flex items-center gap-2">
      <UButton
        :loading="single.status.value === 'pending'"
        :disabled="!selected"
        icon="i-lucide-upload-cloud"
        @click="single.upload('/upload', selected!, {
          fields: { folder: 'avatars', visibility: 'private' }
        })"
      >
        上传文件（携带 fields）
      </UButton>
      <UBadge :color="STATUS[single.status.value].color" variant="subtle">
        {{ single.progress.value ?? 0 }}% · {{ STATUS[single.status.value].label }}
      </UBadge>
    </div>
    <UAlert
      v-if="single.error.value"
      color="error"
      variant="subtle"
      :description="single.error.value.message"
    />
    <UCard v-if="single.data.value">
      <pre class="text-xs overflow-auto">{{ single.data.value }}</pre>
    </UCard>
  </div>
</template>
```

### Timeout

`timeout` sets the upload timeout in milliseconds (0 or omitted means no timeout). On timeout the request is aborted with a `TimeoutError` and `error.data.kind` is `timeout`:

```vue [ComposablesUseUploadProgressTimeoutExample.vue]
<script setup lang="ts">
const STATUS = {
  idle: { color: 'neutral', label: '空闲' },
  pending: { color: 'info', label: '上传中' },
  success: { color: 'success', label: '完成' },
  error: { color: 'error', label: '失败' },
  aborted: { color: 'warning', label: '已取消' }
} as const

const selected = ref<File[] | null>(null)
const timeout = useUploadWithProgress()
</script>

<template>
  <div class="flex flex-col gap-3">
    <UFileUpload v-model="selected" multiple label="选择文件后模拟超时" />
    <div class="flex items-center gap-2">
      <UButton
        color="neutral"
        :loading="timeout.status.value === 'pending'"
        :disabled="!selected?.length"
        icon="i-lucide-timer"
        @click="timeout.upload('/upload?slow=2000', selected!, { timeout: 500 })"
      >
        模拟超时
      </UButton>
      <UBadge :color="STATUS[timeout.status.value].color" variant="subtle">
        {{ STATUS[timeout.status.value].label }}
      </UBadge>
    </div>
    <UAlert
      v-if="timeout.error.value"
      color="error"
      variant="subtle"
      :description="timeout.error.value.message"
    />
  </div>
</template>
```

### Cross-Origin Credentials

```ts
await upload('https://other.example/upload', file, { withCredentials: true })
```

### Abort Upload

```ts
const { status, upload, abort } = useUploadWithProgress()

upload('/api/upload', largeFile)

function handleCancel() {
  if (status.value === 'pending') abort()
}
```

After aborting:

- `status` changes to `'aborted'`; `progress` resets to `0`
- `error` remains `null` (not treated as failure)
- `onSuccess` / `onError` are not called; no Toast is shown
- `upload()` returns `{ data: null, error: null, aborted: true }`

### Authentication

The token is automatically read from the session and injected into the `Authorization` header. You can override it with the same header name in `headers` (user value takes priority).

```ts
await upload('/api/upload', file, {
  headers: { Authorization: 'Bearer override' }
})
```

### API

#### useUploadWithProgress<T>()

`useUploadWithProgress<T>(): { progress, status, data, error, upload, abort }`{lang="ts-type"}

##### Returns

**progress** (`Ref<number | null>`): Upload progress, 0–100. Aligned with the download-side type, null is retained as a possible value but does not occur in practice for uploads.

**status** (`Ref<TransferStatus>`): Transfer status: 'idle' | 'pending' | 'success' | 'error' | 'aborted'.

**data** (`Ref<T | null>`): Business data unwrapped by dataKey.

**error** (`Ref<ApiError | null>`): Error object. Business errors are ApiError; HTTP/network errors are Error. null on abort.

**upload()** (`(url: string, files: File | File[], options?: UploadWithProgressOptions<T>) => Promise<TransferResult<T>>`): Execute the upload.ParametersDefaults to 'file'.Merged with the endpoint headers; when auth is enabled the auth header is injected last and takes the highest priority, same as $api.Whether to validate the business status code; inherits the endpoint config when omitted. When false, still unwraps by dataKey.Whether to unwrap by dataKey; inherits the endpoint config when omitted.Timeout in milliseconds. 0 or omitted means no timeout.Receives the unwrapped business data.ReturnsPromise<TransferResult<T>>: { data: T | null, error: ApiError | null, aborted: boolean }.

**abort()** (`() => void`): Abort the current upload; status switches to 'aborted'.

### Changelog

See commit history for [src/runtime/composables/upload and Download.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/upload and Download.ts).

## useDownloadWithProgress

### Usage

`useDownloadWithProgress` reads a streamed response through `$api.raw` and reports progress, so endpoint headers, auth, business validation, Toast, error normalization and `movk:api:*` hooks match `useApiFetch` exactly; the request body is serialized by ofetch and every failure is an `ApiError`.

When the backend returns `application/json`, business validation is applied and error responses are **not** written to a file as binary. When binary data is returned, progress is calculated from `content-length`; when `content-length` is missing, `progress` is `null` and the UI can switch to indeterminate accordingly.

```vue
<script setup lang="ts">
const { progress, status, error, download, abort } = useDownloadWithProgress()

async function handleDownload() {
  const { aborted, error: err } = await download('/api/export/report', {
    filename: 'monthly-report.pdf',
    onSuccess: name => console.log('Done', name)
  })
  if (aborted) return
  if (err) console.error(err)
}
</script>

<template>
  <UButton :loading="status === 'pending'" @click="handleDownload">Download</UButton>
  <UProgress
    v-if="status === 'pending'"
    :model-value="progress ?? undefined"
    :max="100"
  />
  <UButton v-if="status === 'pending'" @click="abort">Cancel</UButton>
</template>
```

> [!NOTE]
> 
> Use this for large file exports, bulk downloads and similar scenarios. For small files where progress is not needed, use 
> 
> $api
> 
>  directly.

### Basic Download

When `content-length` is known, progress updates proportionally; `abort()` stops the stream read:

```vue [ComposablesUseDownloadProgressBasicExample.vue]
<script setup lang="ts">
const STATUS = {
  idle: { color: 'neutral', label: '空闲' },
  pending: { color: 'info', label: '传输中' },
  success: { color: 'success', label: '完成' },
  error: { color: 'error', label: '失败' },
  aborted: { color: 'warning', label: '已取消' }
} as const

const basic = useDownloadWithProgress()
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2">
      <UButton
        :loading="basic.status.value === 'pending'"
        icon="i-lucide-download"
        @click="basic.download('/download/large')"
      >
        开始下载
      </UButton>
      <UButton
        v-if="basic.status.value === 'pending'"
        color="error"
        variant="soft"
        icon="i-lucide-x"
        @click="basic.abort"
      >
        中止
      </UButton>
      <UBadge :color="STATUS[basic.status.value].color" variant="subtle">
        {{ basic.progress.value ?? 0 }}% · {{ STATUS[basic.status.value].label }}
      </UBadge>
    </div>
    <UProgress :model-value="basic.progress.value ?? undefined" :max="100" />
    <UAlert
      v-if="basic.error.value"
      color="error"
      variant="subtle"
      :description="basic.error.value.message"
    />
  </div>
</template>
```

### Filename Resolution

Priority order:

1. `options.filename`
2. Response header `Content-Disposition` (supports RFC 5987 encoding)
3. Last segment of the URL pathname (query string is automatically stripped)
4. `'download'`

```ts
await download('/api/export?token=abc')
// Automatically uses "export" as the fallback filename; query string does not pollute the name
```

### Indeterminate Progress

When the response is missing `content-length` (e.g. chunked transfer encoding), `progress` is `null`. Using nullish-coalescing to map it to `UProgress`'s `:model-value` automatically activates the indeterminate state:

```vue [ComposablesUseDownloadProgressChunkedExample.vue]
<script setup lang="ts">
const STATUS = {
  idle: { color: 'neutral', label: '空闲' },
  pending: { color: 'info', label: '传输中' },
  success: { color: 'success', label: '完成' },
  error: { color: 'error', label: '失败' },
  aborted: { color: 'warning', label: '已取消' }
} as const

const chunked = useDownloadWithProgress()
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2">
      <UButton
        :loading="chunked.status.value === 'pending'"
        icon="i-lucide-download"
        @click="chunked.download('/download/chunked')"
      >
        开始下载
      </UButton>
      <UBadge :color="STATUS[chunked.status.value].color" variant="subtle">
        {{ chunked.progress.value === null ? '不确定' : `${chunked.progress.value}%` }}
        · {{ STATUS[chunked.status.value].label }}
      </UBadge>
    </div>
    <UProgress :model-value="chunked.progress.value ?? undefined" :max="100" />
  </div>
</template>
```

### Custom Filename

`options.filename` overrides the response header and URL inference to force a specific download filename:

```vue [ComposablesUseDownloadProgressCustomExample.vue]
<script setup lang="ts">
const STATUS = {
  idle: { color: 'neutral', label: '空闲' },
  pending: { color: 'info', label: '传输中' },
  success: { color: 'success', label: '完成' },
  error: { color: 'error', label: '失败' },
  aborted: { color: 'warning', label: '已取消' }
} as const

const custom = useDownloadWithProgress()
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2">
      <UButton
        :loading="custom.status.value === 'pending'"
        icon="i-lucide-file-down"
        @click="custom.download('/download/large', { filename: 'custom-name.bin' })"
      >
        自定义文件名下载
      </UButton>
      <UBadge :color="STATUS[custom.status.value].color" variant="subtle">
        {{ STATUS[custom.status.value].label }}
      </UBadge>
    </div>
    <UAlert
      v-if="custom.error.value"
      color="error"
      variant="subtle"
      :description="custom.error.value.message"
    />
  </div>
</template>
```

### POST Export

`method: 'POST'` + `body` puts filter criteria in the request body; `Content-Type` is automatically set to `application/json`:

```vue [ComposablesUseDownloadProgressPostExample.vue]
<script setup lang="ts">
const STATUS = {
  idle: { color: 'neutral', label: '空闲' },
  pending: { color: 'info', label: '传输中' },
  success: { color: 'success', label: '完成' },
  error: { color: 'error', label: '失败' },
  aborted: { color: 'warning', label: '已取消' }
} as const

const postExport = useDownloadWithProgress()
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2">
      <UButton
        :loading="postExport.status.value === 'pending'"
        icon="i-lucide-package"
        @click="postExport.download('/download/large', {
          method: 'POST',
          body: { ids: [1, 2, 3] }
        })"
      >
        POST 导出
      </UButton>
      <UBadge :color="STATUS[postExport.status.value].color" variant="subtle">
        {{ STATUS[postExport.status.value].label }}
      </UBadge>
    </div>
    <UAlert
      v-if="postExport.error.value"
      color="error"
      variant="subtle"
      :description="postExport.error.value.message"
    />
  </div>
</template>
```

### Abort Download

```ts
const { status, download, abort } = useDownloadWithProgress()

download('/api/export/large.zip')

function handleCancel() {
  if (status.value === 'pending') abort()
}
```

After aborting:

- `status` changes to `'aborted'`; `progress` resets to `0`
- `error` remains `null` (not treated as failure)
- `onError` is not called; no Toast is shown
- `download()` returns `{ data: null, error: null, aborted: true }`

### Authentication

The token is automatically read from the session and injected into the `Authorization` header. Override it in `headers` if needed (user value takes priority).

```ts
await download('/api/export/private.pdf', {
  headers: { 'X-Custom': 'value' }
})
```

### API

#### useDownloadWithProgress<T>()

`useDownloadWithProgress<T = Blob>(): { progress, status, data, error, download, abort }`{lang="ts-type"}

##### Returns

**progress** (`Ref<number | null>`): Download progress, 0–100. null when content-length is missing; the UI should switch to indeterminate in that case.

**status** (`Ref<TransferStatus>`): Transfer status: 'idle' | 'pending' | 'success' | 'error' | 'aborted'.

**data** (`Ref<T | null>`): In the binary path, a Blob. In the JSON path, the unwrapped business data.

**error** (`Ref<ApiError | null>`): Error object. Business errors are ApiError; HTTP/network errors are Error. null on abort.

**download()** (`(url: string, options?: DownloadWithProgressOptions) => Promise<TransferResult<T>>`): Execute the download.ParametersDefaults to 'GET'.Serialized to JSON for non-GET requests.Merged with the endpoint headers; when auth is enabled the auth header is injected last and takes the highest priority, same as $api.Whether to validate the business status code; inherits the endpoint config when omitted. When false, still unwraps by dataKey.Whether to unwrap by dataKey; inherits the endpoint config when omitted.ReturnsPromise<TransferResult<T>>: { data: T | null, error: ApiError | null, aborted: boolean }.

**abort()** (`() => void`): Abort the current download; status switches to 'aborted'.

### Changelog

See commit history for [src/runtime/composables/upload and Download.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/upload and Download.ts).


## Sitemap

See the full [sitemap](https://nuxt.mhaibaraai.cn/sitemap.md) for all pages.
