useUploadWithProgress
用法
useUploadWithProgress 以 XHR 适配器作为底层 fetch 接入 $api 同一条管线(fetch 规范在主流浏览器上仍无法报告上传进度),端点请求头、认证、业务校验、Toast、错误归一与 movk:api:* hook 与 useApiFetch 完全一致。返回的 data 按端点策略解包,失败统一为 ApiError。
<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('上传成功:', 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">上传</UButton>
<UProgress v-if="status === 'pending'" :model-value="progress ?? undefined" :max="100" />
<UButton v-if="status === 'pending'" @click="abort">取消</UButton>
</template>
$api 发起请求。基础多文件上传
fieldName 决定 FormData 字段名(默认 'file');upload() 返回 { data, error, aborted }:
<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>
单文件、多文件与额外字段
files 传 File 为单文件、传 File[] 为多文件(同 fieldName 追加);fields 注入额外表单字段一并提交:
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' }
})
<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 设定上传超时毫秒数(0 或省略不超时),超时后以 TimeoutError 中止,error.data.kind 为 timeout:
<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>
跨域携带凭证
await upload('https://other.example/upload', file, { withCredentials: true })
取消上传
const { status, upload, abort } = useUploadWithProgress()
upload('/api/upload', largeFile)
function handleCancel() {
if (status.value === 'pending') abort()
}
取消后:
status变为'aborted',progress重置为0error保持null(不视为失败)- 不触发
onSuccess/onError,不弹 Toast upload()返回{ data: null, error: null, aborted: true }
认证
自动从 session 读取 token 注入到 Authorization 头;可在 headers 中覆盖同名头(用户优先)。
await upload('/api/upload', file, {
headers: { Authorization: 'Bearer override' }
})
API
useUploadWithProgress<T>()
useUploadWithProgress<T>(): { progress, status, data, error, upload, abort }
Returns
null 形态,上传场景实际不会出现。'idle' | 'pending' | 'success' | 'error' | 'aborted'。dataKey 解包后的业务数据。ApiError,HTTP/网络错误为 Error。中止时为 null。Parameters
'file'。$api 一致。false 时仍按 dataKey 解包。dataKey 解包,未传时继承端点配置。Returns
Promise<TransferResult<T>>:{ data: T | null, error: ApiError | null, aborted: boolean }。
status 切到 'aborted'。Changelog
useDownloadWithProgress
用法
useDownloadWithProgress 基于 $api.raw 以流式响应读取并汇报进度,端点请求头、认证、业务校验、Toast、错误归一与 movk:api:* hook 与 useApiFetch 完全一致;请求体由 ofetch 序列化,失败统一为 ApiError。
后端返回 application/json 时走业务校验,不会把错误响应当作二进制写入文件;返回二进制时按 content-length 计算进度,缺失时 progress 为 null,UI 据此切 indeterminate。
<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('完成', name)
})
if (aborted) return
if (err) console.error(err)
}
</script>
<template>
<UButton :loading="status === 'pending'" @click="handleDownload">下载</UButton>
<UProgress
v-if="status === 'pending'"
:model-value="progress ?? undefined"
:max="100"
/>
<UButton v-if="status === 'pending'" @click="abort">取消</UButton>
</template>
$api 即可。基础下载
content-length 已知时进度按比例更新,abort() 中止流式读取:
<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>
文件名提取
优先级:
options.filename- 响应头
Content-Disposition(支持 RFC 5987 编码) - URL pathname 末段(自动去除 query string)
'download'
await download('/api/export?token=abc')
// 自动取得 export 作为 fallback 文件名,query 不会污染
不确定进度
当响应缺少 content-length(如分块传输),progress 为 null,通过 nullish-coalescing 映射到 UProgress 的 :model-value 即自动进入 indeterminate:
<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>
自定义文件名
options.filename 覆盖响应头与 URL 推断,强制指定下载文件名:
<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 导出
method: 'POST' + body 把筛选条件放进请求体,Content-Type 自动补 application/json:
<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>
取消下载
const { status, download, abort } = useDownloadWithProgress()
download('/api/export/large.zip')
function handleCancel() {
if (status.value === 'pending') abort()
}
取消后:
status变为'aborted',progress重置为0error保持null(不视为失败)- 不触发
onError,不弹 Toast download()返回{ data: null, error: null, aborted: true }
认证
自动从 session 读取 token 注入到 Authorization 头;可在 headers 中覆盖(用户优先)。
await download('/api/export/private.pdf', {
headers: { 'X-Custom': 'value' }
})
API
useDownloadWithProgress<T>()
useDownloadWithProgress<T = Blob>(): { progress, status, data, error, download, abort }
Returns
content-length 时为 null,UI 据此切 indeterminate。'idle' | 'pending' | 'success' | 'error' | 'aborted'。Blob;JSON 路径下为解包后的业务数据。ApiError,HTTP/网络错误为 Error。中止时为 null。Parameters
'GET'。$api 一致。false 时仍按 dataKey 解包。dataKey 解包,未传时继承端点配置。Returns
Promise<TransferResult<T>>:{ data: T | null, error: ApiError | null, aborted: boolean }。
status 切到 'aborted'。