Upload
Select files by clicking or dropping, upload them to a server, and display their list and upload progress.
Import
import { HuiUpload, createChunkUpload } from '@nscode/handy-ui'
Basic Usage
action is the upload URL. Selected files are uploaded immediately with POST under the field specified by name, defaulting to file. In an application, use <HuiUpload action="/api/upload" />; see Connecting a Real API below for a complete integration.
This page has no real upload endpoint. Examples provide http-request to simulate uploading with timers: progress increases by 20% every 200 milliseconds and succeeds at 100%, without sending files.
<script setup lang="ts">
import { HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest } from '@nscode/handy-ui'
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload :http-request="mockUpload" />
</template>
The component maintains its own file list when file-list is omitted.
Controlled File Lists
Bind the list with v-model:file-list to display existing files and read their ready, uploading, success, or error status. The example below displays each bound file's status and progress; select several files to observe updates.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiUpload } from '@nscode/handy-ui'
import type { UploadFile, UploadHttpRequest } from '@nscode/handy-ui'
const fileList = ref<UploadFile[]>([
{ uid: 1, name: 'report.pdf', status: 'success', url: '/files/report.pdf' }
])
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload v-model:file-list="fileList" :http-request="mockUpload" multiple />
<div class="file-state">
<div v-for="file in fileList" :key="file.uid">
{{ file.name }}:{{ file.status
}}{{ file.status === 'uploading' ? ` ${file.progress}%` : '' }}
</div>
</div>
</template>
<style scoped>
.file-state {
margin-top: 12px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
line-height: 1.8;
}
</style>
Drag and Drop
drag displays a drop zone with an upload icon and localized instructions. Dropped files undergo the same accept and max-size checks as files selected through the picker. Without multiple, only the first eligible file is used. The drop zone supports Tab focus and Enter/Space to open the file picker.
<script setup lang="ts">
import { HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest } from '@nscode/handy-ui'
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload :http-request="mockUpload" drag accept="image/*" />
</template>
The trigger slot replaces the drop zone's icon and text. The default slot appears after the file list, useful for guidance:
<script setup lang="ts">
import { HuiIcon, HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest } from '@nscode/handy-ui'
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload :http-request="mockUpload" drag multiple>
<template #trigger>
<HuiIcon name="folder" size="lg" />
<div>Drop scanned contracts here; multiple files are allowed</div>
</template>
<p class="tip">Supports pdf, jpg, and png; at most 10MB per file</p>
</HuiUpload>
</template>
<style scoped>
.tip {
margin-top: 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
File Type, Count, and Size Limits
acceptfollows native input syntax: dot-prefixed extensions such as.jpg,.png(case-insensitive), or MIME types such as image/* and application/pdf, separated by commas. Native accept only filters the picker by default, and users can choose All files, so the component rechecks both selected and dropped files.max-sizeis the per-file limit in bytes, for example5 * 1024 * 1024for 5MB.- Unsupported or oversized files are not added or uploaded. Each emits reject once, with the reason 'type' or 'size' as its second argument. The component does not display a message automatically; handle reject for feedback.
limitcaps the total file count. An over-limit batch is rejected as a whole and emits exceed. Files rejected by earlier checks are excluded from the count.
<script setup lang="ts">
import { HuiMessage, HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest, UploadRejectReason } from '@nscode/handy-ui'
const maxSize = 5 * 1024 * 1024
const onReject = (file: File, reason: UploadRejectReason) => {
if (reason === 'type')
HuiMessage.warning(`${file.name} has an unsupported format; only jpg and png are allowed`)
else HuiMessage.warning(`${file.name} exceeds 5MB`)
}
const onExceed = () => HuiMessage.warning('At most 3 files')
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload
:http-request="mockUpload"
accept=".jpg,.png"
:max-size="maxSize"
:limit="3"
multiple
@reject="onReject"
@exceed="onExceed"
>
<p>Only jpg and png; at most 5MB each and 3 files total</p>
</HuiUpload>
</template>
Files are checked in this order: accept → max-size → limit → before-upload. A file failing both type and size checks emits reject once with reason 'type'.
Use before-upload for additional checks such as image dimensions. Returning false skips the file. It also accepts a Promise: resolving false or rejecting skips the file, while resolving a File uploads the returned file, such as a compressed image. Other files continue normally.
The following before-upload skips filenames containing spaces. Other files undergo a simulated 300ms check, then upload a new File whose name has the original 已检查- sample prefix:
<script setup lang="ts">
import { HuiMessage, HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest } from '@nscode/handy-ui'
const beforeUpload = async (file: File) => {
if (/\s/.test(file.name)) {
HuiMessage.warning(`${file.name} contains spaces in its name and was skipped`)
return false
}
// Simulate an asynchronous check, such as image dimensions, passing after 300ms
await new Promise((resolve) => setTimeout(resolve, 300))
// Return a new File for both uploading and display
return new File([file], `已检查-${file.name}`, { type: file.type })
}
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload :http-request="mockUpload" :before-upload="beforeUpload" multiple />
</template>
Per-File Waiting, Transformation, and Stale Results
beforeUpload distinguishes original File objects, using the latest request for each. Returning a File synchronously or asynchronously preserves the transformed result; type and size checks still use the original file. Only false, a thrown error, or rejection blocks the file; undefined allows it. Development warnings for errors include the hook name. The limit is rechecked after waiting so concurrent selections cannot exceed it.
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace, HuiSwitch, HuiUpload } from '@nscode/handy-ui'
import type { UploadExpose, UploadFile } from '@nscode/handy-ui'
interface WaitingUpload {
id: number
file: File
resolve: (value: File | boolean | void) => void
}
const control = ref<UploadExpose>()
const files = ref<UploadFile[]>([])
const disabled = ref(false)
const pending = ref<WaitingUpload[]>([])
const event = ref('Waiting for file selection')
let seed = 0
const pendingClear = ref(false)
let alive = true
let version = 0
watch([files, pending, disabled], () => version++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
version++
})
const beforeUpload = (file: File) =>
new Promise<File | boolean | void>((resolve) => {
pending.value.push({ id: ++seed, file, resolve })
event.value = 'Waiting for approval: ' + file.name
})
const release = (request: WaitingUpload, choice: 'allow' | 'transform' | 'block') => {
pending.value = pending.value.filter((item) => item.id !== request.id)
const result =
choice === 'block'
? false
: choice === 'transform'
? new File([request.file], 'converted-' + request.file.name, { type: request.file.type })
: undefined
request.resolve(result)
event.value = (choice === 'block' ? 'Blocked: ' : 'Allowed: ') + request.file.name
}
const clear = async () => {
if (
!alive ||
disabled.value ||
pendingClear.value ||
(!files.value.length && !pending.value.length)
)
return
const request = version
pendingClear.value = true
const snapshot = [...files.value]
const requests = [...pending.value]
try {
await HuiMessageBox.confirm(
`Clear all ${snapshot.length} files and invalidate ${requests.length} pending upload requests?`
)
} catch {
if (alive && version === request) event.value = 'Cancelled; no operations performed'
if (alive) pendingClear.value = false
return
}
if (
!alive ||
disabled.value ||
version !== request ||
snapshot.length !== files.value.length ||
snapshot.some((file, index) => file !== files.value[index]) ||
requests.length !== pending.value.length ||
requests.some((request, index) => request !== pending.value[index])
) {
if (alive) {
event.value = 'The records changed; confirm again'
pendingClear.value = false
}
return
}
control.value?.clearFiles()
if (alive) pendingClear.value = false
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch v-model="disabled" active-text="Pause (invalidate old hooks)" />
<HuiButton
:disabled="disabled || pendingClear || (!files.length && !pending.length)"
@click="clear"
>Confirm before cancelling all</HuiButton
>
</HuiSpace>
<HuiUpload
ref="control"
v-model:file-list="files"
multiple
:limit="2"
:auto-upload="false"
:disabled="disabled"
:before-upload="beforeUpload"
@exceed="event = 'exceed'"
@change="event = 'change: ' + $event.name"
@remove="event = 'remove: ' + $event.name"
/>
<HuiSpace v-for="request in pending" :key="request.id" wrap>
<span>{{ request.file.name }}</span>
<HuiButton @click="release(request, 'allow')">Allow the original file</HuiButton>
<HuiButton @click="release(request, 'transform')">Transform and allow</HuiButton>
<HuiButton @click="release(request, 'block')">Block this file</HuiButton>
</HuiSpace>
<span>{{ event }}; Current list: {{ files.map((file) => file.name).join(', ') }}</span>
<span
>Select multiple files and allow each separately. limit=2 prevents excess entries. Old
requests may still resolve after cancellation, but their results are ignored.</span
>
</HuiSpace>
</template>
Confirming Removal
before-remove lets application code approve removal. Only false, a Promise resolving false, a thrown error, or rejection blocks it; undefined allows it. Without the hook, removal is immediate. Repeated removal requests for a pending file have no effect; the button is dimmed but remains focusable. Active uploads are cancelled only after the hook allows removal.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiUpload, HuiMessageBox } from '@nscode/handy-ui'
import type { UploadFile } from '@nscode/handy-ui'
const files = ref<UploadFile[]>([
{ uid: 1, name: 'project-brief.pdf', status: 'success' },
{ uid: 2, name: 'attachment.txt', status: 'success' }
])
const beforeRemove = (file: UploadFile) =>
HuiMessageBox.confirm(
`Remove file “${file.name.trim() || 'Unnamed file'}” (UID ${file.uid})? Only this list entry will be removed. Any active local upload will be cancelled; no server-file deletion is requested.`,
'Notice',
{ type: 'warning' }
)
.then(() => true)
.catch(() => false)
</script>
<template>
<HuiUpload v-model:file-list="files" :auto-upload="false" :before-remove="beforeRemove" />
</template>
Manual Uploading
With auto-upload=false, selected files only enter the list until submit() is called. abort() cancels active uploads and returns them to ready so they can be submitted again. clearFiles() clears the list, or only files matching a status array, and cancels those files' active uploads.
This example slows the simulated upload to 5 seconds so you can cancel it. "Remove completed files" and "Clear all" ask for confirmation first and clean up only after you confirm. You can clear the list while files are uploading; their active uploads are cancelled too. If the upload is switched to read-only while the dialog is open, nothing is cleared and a message says so. Cleanup affects only local list entries and their local uploads; it does not request deletion of server files:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace, HuiSwitch, HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest, UploadExpose, UploadFile } from '@nscode/handy-ui'
const uploadRef = ref<UploadExpose>()
// Simulate uploading: add 10% every 500ms without a network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 10
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 500)
return { abort: () => clearInterval(timer) }
}
const files = ref<UploadFile[]>([])
const readonly = ref(false)
const pendingClear = ref(false)
const feedback = ref('Waiting for an action')
// Without statuses, everything is cleared; clearFiles also cancels active uploads
const clearConfirmed = async (statuses?: UploadFile['status'][]) => {
pendingClear.value = true
try {
await HuiMessageBox.confirm(
`${statuses ? 'Remove completed files' : 'Clear all files'}? Active uploads are cancelled too; no server-file deletion is requested.`,
'Confirm file-list cleanup',
{ type: 'warning' }
)
} catch {
feedback.value = 'Cancelled; the file list and uploads are unchanged'
return
} finally {
pendingClear.value = false
}
// The example was unmounted or switched to read-only while confirming: do nothing
if (!uploadRef.value || readonly.value) {
feedback.value = 'The upload is read-only; nothing was cleared'
return
}
const count = statuses
? files.value.filter((file) => file.status && statuses.includes(file.status)).length
: files.value.length
uploadRef.value.clearFiles(statuses)
feedback.value = `Removed ${count} file entries`
}
</script>
<template>
<HuiUpload
v-model:file-list="files"
:disabled="readonly"
ref="uploadRef"
:http-request="mockUpload"
:auto-upload="false"
multiple
/>
<div style="margin-top: 12px">
<HuiSpace wrap>
<HuiSwitch v-model="readonly" active-text="Read-only (disable upload and cleanup)" />
<HuiButton type="primary" :disabled="readonly" @click="uploadRef?.submit()"
>Start uploading</HuiButton
>
<HuiButton :disabled="readonly" @click="uploadRef?.abort()">Cancel uploading</HuiButton>
<HuiButton
:disabled="readonly || pendingClear || !files.some((file) => file.status === 'success')"
@click="clearConfirmed(['success'])"
>Remove completed files</HuiButton
>
<HuiButton :disabled="readonly || pendingClear || !files.length" @click="clearConfirmed()"
>Clear all</HuiButton
>
</HuiSpace>
</div>
<p>{{ feedback }}</p>
</template>
Custom Upload Requests
http-request replaces the default XHR upload. Return a Promise, resolving for success or rejecting for failure, or an object with an abort method and call onProgress, onSuccess, and onError yourself.
import type { UploadHttpRequest } from '@nscode/handy-ui'
// Return a Promise
const httpRequest: UploadHttpRequest = ({ file }) => api.upload(file)
// Return { abort } to report progress
const httpRequestWithProgress: UploadHttpRequest = ({ file, onProgress, onSuccess, onError }) => {
const controller = new AbortController()
api
.upload(file, { signal: controller.signal, onProgress: (percent) => onProgress({ percent }) })
.then(onSuccess, onError)
return { abort: () => controller.abort() }
}
Try both forms below. The left returns a Promise that completes after 1 second without progress updates. The right returns { abort } and reports progress. Simulate failure calls onError at 60%, marking the file as failed and emitting error.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCheckbox, HuiMessage, HuiSpace, HuiUpload } from '@nscode/handy-ui'
import type { UploadFile, UploadHttpRequest } from '@nscode/handy-ui'
const shouldFail = ref(false)
// Return a Promise: its resolved value is the success event's response
const promiseUpload: UploadHttpRequest = ({ file }) =>
new Promise((resolve) => setTimeout(() => resolve({ name: file.name }), 1000))
// Return { abort }: report progress, success, and failure manually
const progressUpload: UploadHttpRequest = ({ onProgress, onSuccess, onError }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
if (shouldFail.value && percent === 60) {
clearInterval(timer)
onError(new Error('Network interrupted; upload failed'))
return
}
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 300)
return { abort: () => clearInterval(timer) }
}
const onError = (error: Error, file: UploadFile) => {
HuiMessage.error(`${file.name}: ${error.message}`)
}
</script>
<template>
<HuiSpace wrap align="start" size="large">
<HuiUpload :http-request="promiseUpload">
<p>Return a Promise</p>
</HuiUpload>
<HuiUpload :http-request="progressUpload" @error="onError">
<HuiCheckbox v-model="shouldFail">Simulate failure</HuiCheckbox>
</HuiUpload>
</HuiSpace>
</template>
http-request also receives action, name, headers, data, and withCredentials from the corresponding props. Use them when implementing a request. The example below displays the received arguments:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest, UploadRequestOptions } from '@nscode/handy-ui'
const received = ref('')
const mockUpload: UploadHttpRequest = (options: UploadRequestOptions) => {
const { file, action, name, headers, data, withCredentials } = options
received.value = JSON.stringify(
{ file: file.name, action, name, headers, data, withCredentials },
null,
2
)
return new Promise((resolve) => setTimeout(resolve, 500))
}
</script>
<template>
<HuiUpload
action="/api/attachments"
name="attachment"
:headers="{ 'X-Tenant': 'demo' }"
:data="{ bizType: 'contract', bizId: 42 }"
with-credentials
:http-request="mockUpload"
/>
<pre class="received">{{
received || 'Choose a file to display http-request arguments here'
}}</pre>
</template>
<style scoped>
.received {
margin-top: 12px;
padding: var(--hui-spacing-3);
border-radius: var(--hui-border-radius);
background-color: var(--hui-fill-color-light);
color: var(--hui-text-color-secondary);
font-family: var(--hui-font-family-mono);
font-size: var(--hui-font-size-sm);
white-space: pre-wrap;
}
</style>
Chunked and Resumable Uploads
createChunkUpload(adapter, options) returns an http-request function handling chunking, resuming, concurrency, retries, progress, and cancellation. The adapter supplies endpoint URLs, request formats, and authentication. This in-memory example loses simulated server records on refresh. Select a large file, cancel, then resume to see completed chunks skipped.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { createChunkUpload, HuiButton, HuiSpace, HuiUpload } from '@nscode/handy-ui'
import type { UploadFile, UploadExpose } from '@nscode/handy-ui'
const uploadRef = ref<UploadExpose>()
const files = ref<UploadFile[]>([])
const uploading = computed(() => files.value.some((file) => file.status === 'uploading'))
const result = ref('Choose a file to start; this example sends no files over the network.')
const sessions = new Map<string, Set<number>>()
const chunkUpload = createChunkUpload(
{
init: async ({ fileId }) => {
if (!sessions.has(fileId)) sessions.set(fileId, new Set())
return {
uploadId: fileId,
chunkSize: 512 * 1024,
uploadedChunks: [...sessions.get(fileId)!]
}
},
uploadChunk: ({ uploadId, index, chunk, signal, onProgress }) =>
new Promise<void>((resolve, reject) => {
if (signal.aborted) {
reject(new Error('Upload cancelled'))
return
}
const cancel = () => {
clearTimeout(timer)
reject(new Error('Upload cancelled'))
}
const timer = setTimeout(() => {
signal.removeEventListener('abort', cancel)
onProgress(chunk.size)
sessions.get(uploadId)!.add(index)
resolve()
}, 300)
signal.addEventListener('abort', cancel, { once: true })
}),
complete: async ({ file, chunkCount }) => {
result.value = `${file.name}: ${chunkCount} chunks merged`
return { name: file.name, chunkCount }
}
// Omit abort: retain chunks after cancellation so this example can resume.
},
{ concurrency: 2 }
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiUpload ref="uploadRef" v-model:file-list="files" :http-request="chunkUpload" />
<HuiSpace>
<HuiButton :disabled="!uploading" @click="uploadRef?.abort()">Cancel this upload</HuiButton>
<HuiButton
:disabled="uploading || !files.some((file) => file.status === 'ready')"
@click="uploadRef?.submit()"
>Resume uploading</HuiButton
>
</HuiSpace>
<span>{{ result }}</span>
</HuiSpace>
</template>
Every adapter method receives the original request, including headers, data, and action. Connect uploadChunk's signal to the request library's cancellation support and report uploaded bytes through onProgress. A failed chunk retries 3 times by default, after 1, 2, and 4 seconds. Exhausting retries stops other chunks while retaining server records. complete runs after all chunks upload; total progress remains at most 99% until merging succeeds.
The default file identifier combines filename, size, lastModified, and configured chunk size. It reduces accidental matches but does not prove identical content. For content-based resuming or instant completion, supply a custom fileId, for example:
// Second argument to createChunkUpload; calculate large-file digests in a Worker.
const options = {
fileId: async (file: File) => {
const sampleSize = 2 * 1024 * 1024
const starts = new Set([
0,
Math.max(0, Math.floor((file.size - sampleSize) / 2)),
Math.max(0, file.size - sampleSize)
])
const sample = new Blob([
...Array.from(starts, (start) => file.slice(start, start + sampleSize)),
String(file.size)
])
const digest = await crypto.subtle.digest('SHA-256', await sample.arrayBuffer())
return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, '0')).join(
''
)
}
}
A sampled digest does not prove identical full-file content. Instant completion must be confirmed by the server using a full hash or post-merge verification. Include the configured chunk size in a custom fileId, or return the server's chunkSize from init, to avoid reusing chunk indices across different sizes.
Web Crypto digests require a supported secure context. adapter.init may return a server-selected chunkSize, uploadedChunks, or completed: { response } for instant completion. The server must configure CORS, authentication headers, and credentials for cross-origin APIs; the utility does not configure the server.
Cancellation stops local retries and subsequent callbacks and calls the optional adapter.abort for cleanup. If that method deletes server chunks, a later attempt reuploads them. Cleanup also runs if uploadId arrives after initialization was cancelled. init and complete receive optional signals to pass to the request library. A late instant-completion result does not delete the complete server file.
Picture Lists and Picture Cards
list-type=picture shows a thumbnail for each file; picture-card uses 148px cards. Image files without a URL generate a preview from the local file.
In picture-card mode, the upload trigger is a dashed 148px + tile after the cards, including when empty, instead of a text upload button. trigger-slot content replaces the + icon inside it. With drag enabled, the trigger remains a drop zone.
<script setup lang="ts">
import { HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest } from '@nscode/handy-ui'
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload :http-request="mockUpload" list-type="picture-card" accept="image/*" />
</template>
Compare all three list types below, each initialized with two existing images. Select more files to see percentage text in text mode and progress bars in the picture modes.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiUpload } from '@nscode/handy-ui'
import type { UploadFile, UploadHttpRequest } from '@nscode/handy-ui'
const createList = (): UploadFile[] => [
{ uid: 1, name: 'cat.jpg', status: 'success', url: '/images/cat.jpg' },
{ uid: 2, name: 'cover.png', status: 'success', url: '/images/cover.png' }
]
const textList = ref(createList())
const pictureList = ref(createList())
const cardList = ref(createList())
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 300)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiSpace direction="vertical" fill size="large">
<div>
<div class="row-label">text (default)</div>
<HuiUpload
v-model:file-list="textList"
:http-request="mockUpload"
accept="image/*"
multiple
/>
</div>
<div>
<div class="row-label">picture</div>
<HuiUpload
v-model:file-list="pictureList"
:http-request="mockUpload"
list-type="picture"
accept="image/*"
multiple
/>
</div>
<div>
<div class="row-label">picture-card</div>
<HuiUpload
v-model:file-list="cardList"
:http-request="mockUpload"
list-type="picture-card"
accept="image/*"
multiple
/>
</div>
</HuiSpace>
</template>
<style scoped>
.row-label {
margin-bottom: 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
The picture-card trigger slot replaces the + icon. Enabling drag changes that trigger into a drop zone:
<script setup lang="ts">
import { HuiIcon, HuiSpace, HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest } from '@nscode/handy-ui'
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiSpace direction="vertical" fill size="large">
<HuiUpload :http-request="mockUpload" list-type="picture-card" accept="image/*" multiple>
<template #trigger>
<div class="card-trigger">
<HuiIcon name="image" size="lg" />
<span>Upload photos</span>
</div>
</template>
</HuiUpload>
<HuiUpload :http-request="mockUpload" list-type="picture-card" accept="image/*" drag multiple />
</HuiSpace>
</template>
<style scoped>
.card-trigger {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--hui-spacing-2);
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
A Single Image
For a single image, such as an avatar, set limit to 1 and hide the + tile with CSS while an image exists; the component does not hide it automatically. The tile reappears after removal.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiUpload } from '@nscode/handy-ui'
import type { UploadFile, UploadHttpRequest } from '@nscode/handy-ui'
const fileList = ref<UploadFile[]>([
{ uid: 1, name: 'avatar.jpg', status: 'success', url: '/images/avatar.jpg' }
])
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload
v-model:file-list="fileList"
:class="{ 'avatar-upload--full': fileList.length >= 1 }"
:http-request="mockUpload"
:limit="1"
list-type="picture-card"
accept="image/*"
/>
</template>
<style scoped>
.avatar-upload--full :deep(.hui-upload__trigger--picture-card) {
display: none;
}
</style>
Custom Triggers
The trigger slot replaces the default upload button with custom content. The default slot appears after the file list.
<script setup lang="ts">
import { HuiButton, HuiUpload } from '@nscode/handy-ui'
import type { UploadHttpRequest } from '@nscode/handy-ui'
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload :http-request="mockUpload" multiple>
<template #trigger>
<HuiButton type="primary" icon="upload">Select attachments</HuiButton>
</template>
<p class="tip">Multiple files can be selected at once</p>
</HuiUpload>
</template>
<style scoped>
.tip {
margin-top: 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Disabled State
disabled prevents file selection, dims drop-zone and picture-card triggers, and disables file removal buttons.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiUpload } from '@nscode/handy-ui'
import type { UploadFile } from '@nscode/handy-ui'
const fileList = ref<UploadFile[]>([
{ uid: 1, name: 'report.pdf', status: 'success', url: '/files/report.pdf' }
])
const pictures = ref<UploadFile[]>([
{ uid: 2, name: 'cat.jpg', status: 'success', url: '/images/cat.jpg' }
])
</script>
<template>
<HuiSpace direction="vertical" fill size="large">
<HuiUpload v-model:file-list="fileList" disabled />
<HuiUpload drag disabled />
<HuiUpload v-model:file-list="pictures" list-type="picture-card" disabled />
</HuiSpace>
</template>
Interaction Events
Selection, upload, and removal events are listed newest first below. This example accepts only images, at most 1MB each and 3 files total. Invalid selections demonstrate reject and exceed.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiUpload } from '@nscode/handy-ui'
import type {
UploadFile,
UploadHttpRequest,
UploadProgressEvent,
UploadRejectReason
} from '@nscode/handy-ui'
const logs = ref<string[]>([])
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 8)
}
const onChange = (file: UploadFile) => log(`change: ${file.name}`)
const onProgress = (event: UploadProgressEvent, file: UploadFile) => {
log(`progress: ${file.name} ${event.percent}%`)
}
const onSuccess = (_response: unknown, file: UploadFile) => log(`success: ${file.name}`)
const onRemove = (file: UploadFile) => log(`remove: ${file.name}`)
const onExceed = (files: File[]) =>
log(`exceed: selected ${files.length} files, exceeding the limit of 3`)
const onReject = (file: File, reason: UploadRejectReason) => {
log(`reject: ${file.name}, reason ${reason}`)
}
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 50
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 300)
return { abort: () => clearInterval(timer) }
}
</script>
<template>
<HuiUpload
:http-request="mockUpload"
accept="image/*"
:max-size="1024 * 1024"
:limit="3"
multiple
@change="onChange"
@progress="onProgress"
@success="onSuccess"
@remove="onRemove"
@exceed="onExceed"
@reject="onReject"
/>
<div class="event-log">
<div v-for="(item, index) in logs" :key="index">{{ item }}</div>
<div v-if="!logs.length">No events yet</div>
</div>
</template>
<style scoped>
.event-log {
margin-top: 12px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
line-height: 1.8;
}
</style>
Upload failures emit error; see Simulate failure in Custom Upload Requests above.
Form Integration
Within HuiFormItem, adding, removing, or clearing files triggers change validation. A disabled form prevents selecting and removing files. Set :validate-event=false to disable validation triggers.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiMessage, HuiUpload } from '@nscode/handy-ui'
import type { UploadFile, UploadHttpRequest } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const form = reactive<{ files: UploadFile[] }>({ files: [] })
// Simulate uploading with a timer; no network request
const mockUpload: UploadHttpRequest = ({ onProgress, onSuccess }) => {
let percent = 0
const timer = setInterval(() => {
percent += 20
onProgress({ percent })
if (percent === 100) {
clearInterval(timer)
onSuccess({ code: 0 })
}
}, 200)
return { abort: () => clearInterval(timer) }
}
const submit = async () => {
const { valid } = await formRef.value!.validate()
if (valid) HuiMessage.success(`Submitted ${form.files.length} attachments`)
}
</script>
<template>
<HuiForm
ref="formRef"
:model="form"
:rules="{
files: [{ type: 'array', required: true, message: 'Upload an attachment', trigger: 'change' }]
}"
>
<HuiFormItem label="Attachments" prop="files">
<HuiUpload v-model:file-list="form.files" :http-request="mockUpload" />
</HuiFormItem>
<HuiFormItem>
<HuiButton type="primary" @click="submit">Submit</HuiButton>
</HuiFormItem>
</HuiForm>
</template>
Connecting a Real API
Provide action for an XHR POST using multipart/form-data. The file uses the name field, defaulting to file; data fields and headers are included, and with-credentials sends cookies. The response is parsed as JSON and passed to success; non-2xx status emits error. The following integration fragment expects your application's credential helper in place of @/utils/auth:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiMessage, HuiUpload } from '@nscode/handy-ui'
import type { UploadFile } from '@nscode/handy-ui'
import { getToken } from '@/utils/auth'
const fileList = ref<UploadFile[]>([])
const headers = { Authorization: `Bearer ${getToken()}` }
// Assume { code: 0, data: { url } }: store the URL in the list for form submission
const onSuccess = (response: unknown, file: UploadFile) => {
const res = response as { code: number; msg?: string; data?: { url: string } }
if (res.code !== 0) {
HuiMessage.error(res.msg ?? `${file.name} upload failed`)
return
}
file.url = res.data?.url
}
const onError = (error: Error, file: UploadFile) => {
HuiMessage.error(`${file.name}: ${error.message}`)
}
</script>
<template>
<HuiUpload
v-model:file-list="fileList"
action="/api/upload"
name="file"
:headers="headers"
:data="{ bizType: 'contract' }"
with-credentials
multiple
@success="onSuccess"
@error="onError"
/>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| action | string | '' | Upload URL |
| headers | Record<string, string> | - | Request headers |
| multiple | boolean | false | Whether multiple selection is allowed |
| data | Record<string, unknown> | - | Additional form fields. Blob and File values are sent as files; other values become strings |
| name | string | 'file' | File field name |
| withCredentials | boolean | false | Whether to send cookies |
| accept | string | '' | Accepted file types, checked for both selection and dropping; failures emit reject |
| maxSize | number | - | Per-file size limit in bytes; violations emit reject. Omit for no limit |
| limit | number | - | Maximum file count |
| autoUpload | boolean | true | Whether selection starts uploading immediately |
| fileList | UploadFile[] | - | File list, supporting v-model:file-list; maintained internally when omitted |
| disabled | boolean | false | Whether disabled |
| drag | boolean | false | Whether to display a drop zone |
| listType | 'text' | 'picture' | 'picture-card' | 'text' | File-list appearance |
| httpRequest | UploadHttpRequest | - | Custom upload request |
| beforeUpload | (file: File) => File | boolean | void | Promise<File | boolean | void> | - | Latest request per original File wins. Only false, errors, or rejection block; undefined allows and File transforms |
| beforeRemove | (file: UploadFile, fileList: UploadFile[]) => boolean | void | Promise<boolean | void> | - | Pending removal is exclusive per UID, with independent files. undefined allows; clearFiles bypasses this hook |
| validateEvent | boolean | true | Whether file-list changes trigger form-item validation |
Events
| Event | Callback arguments | Description |
|---|---|---|
| update:fileList | (fileList: UploadFile[]) | Emitted when the file list changes |
| change | (file: UploadFile, fileList: UploadFile[]) | Emitted when a new file enters the list |
| progress | (event: UploadProgressEvent, file: UploadFile, fileList: UploadFile[]) | Emitted on upload progress updates |
| success | (response: unknown, file: UploadFile, fileList: UploadFile[]) | Emitted on upload success |
| error | (error: Error, file: UploadFile, fileList: UploadFile[]) | Emitted on upload failure. Default request error messages are localized, including the status code for non-2xx responses |
| remove | (file: UploadFile, fileList: UploadFile[]) | Emitted when a removal button removes a file |
| exceed | (files: File[], fileList: UploadFile[]) | Emitted when the selected files exceed limit |
| reject | (file: File, reason: UploadRejectReason) | Emitted once per file failing accept ('type') or maxSize ('size') |
Slots
| Slot | Description |
|---|---|
| trigger | Replace the default upload button, picture-card + icon, or drop-zone icon and text |
| default | Content after the file list, such as guidance |
Methods
| Name | Type | Description |
|---|---|---|
| submit | () => void | Upload all ready files |
| abort | (file?: UploadFile) => void | Cancel uploads, returning them to ready for another submit(). Omit the file to cancel all |
| clearFiles | (statuses?: UploadFile['status'][]) => void | Clear all files, or only the supplied statuses, also cancelling those files' active uploads |
Utilities
| Name | Type | Description |
|---|---|---|
| createChunkUpload | (adapter: ChunkUploadAdapter, options?: ChunkUploadOptions) => UploadHttpRequest | Create a chunked request. Defaults: chunkSize 5MB, concurrency 3, retries 3. Size and concurrency must be positive integers; retries a nonnegative integer |
import { createChunkUpload } from '@nscode/handy-ui'
import type {
ChunkUploadAdapter,
ChunkUploadInitResult,
ChunkUploadOptions
} from '@nscode/handy-ui'
ChunkUploadAdapter provides init, uploadChunk, complete, and optional abort. ChunkUploadInitResult contains uploadId and optional uploadedChunks, chunkSize, and completed. ChunkUploadOptions supports chunkSize, concurrency, retries, and a synchronous or asynchronous fileId(file).
Types
import type {
UploadFile,
UploadStatus,
UploadListType,
UploadRejectReason,
UploadRequestOptions,
UploadHttpRequest,
UploadExpose
} from '@nscode/handy-ui'
type UploadStatus = 'ready' | 'uploading' | 'success' | 'error'
/** type: does not match accept; size: exceeds maxSize */
type UploadRejectReason = 'size' | 'type'
interface UploadFile {
uid: number | string
name: string
size?: number
status?: UploadStatus
progress?: number
url?: string
response?: unknown
raw?: File
}
interface UploadRequestOptions {
file: File
name: string
action: string
headers?: Record<string, string>
data?: Record<string, unknown>
withCredentials?: boolean
onProgress: (event: { percent: number }) => void
onSuccess: (response: unknown) => void
onError: (error: Error) => void
}
type UploadHttpRequest = (
options: UploadRequestOptions
) => { abort: () => void } | Promise<unknown> | void
import type { UploadRequestOptions } from '@nscode/handy-ui'
export interface ChunkUploadInitResult {
/** Upload identifier used for subsequent chunks, merging, and cancellation. */
uploadId: string
/** Zero-based uploaded chunk indices; duplicates and out-of-range indices are ignored. */
uploadedChunks?: number[]
/** Server-selected chunk size in bytes; must be a positive integer. */
chunkSize?: number
/** Return a success response directly when the complete file already exists on the server. */
completed?: { response: unknown }
}
export interface ChunkUploadAdapter {
/** Initialize an upload or query previous progress. */
init: (context: {
file: File
fileId: string
chunkSize: number
chunkCount: number
signal?: AbortSignal
request: UploadRequestOptions
}) => Promise<ChunkUploadInitResult>
/** Upload one chunk, reporting its uploaded bytes through onProgress when supported. */
uploadChunk: (context: {
uploadId: string
index: number
chunk: Blob
signal: AbortSignal
onProgress: (loaded: number) => void
request: UploadRequestOptions
}) => Promise<void>
/** Merge after all chunks succeed; the result is passed to Upload's onSuccess. */
complete: (context: {
uploadId: string
file: File
chunkCount: number
signal?: AbortSignal
request: UploadRequestOptions
}) => Promise<unknown>
/** Clean server-side temporary data after cancellation; failure does not prevent cancellation. */
abort?: (context: { uploadId: string; request: UploadRequestOptions }) => Promise<void> | void
}
export interface ChunkUploadOptions {
/** Bytes per chunk, default 5MB; must be a positive integer. */
chunkSize?: number
/** Concurrent chunk count, default 3; must be a positive integer. */
concurrency?: number
/** Retries per failed chunk, default 3; a nonnegative integer, with delays of 1, 2, and 4 seconds. */
retries?: number
/** Defaults to filename, size, modification time, and configured chunk size; may calculate a sampled digest asynchronously. */
fileId?: (file: File) => string | Promise<string>
}
Focus Methods and Public Types
Use UploadExpose for the component ref. focus() focuses the current, selected, or first available control without changing values or opening the file picker. Disabled or unmounted controls are not focused; read-only focusability follows the existing control contract. blur() affects only this component's active element in its own document, preserving external focus. Focus and blur are emitted once on entering or leaving the group, not for internal movement. Existing form validation remains unchanged.
abort(), submit(), and clearFiles(statuses?) retain their existing contracts. UploadInstance remains a deprecated alias of UploadExpose until 1.0.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiUpload, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { UploadExpose } from '@nscode/handy-ui'
const control = ref<UploadExpose>()
const value = ref(null)
const event = ref('Waiting for an action')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @mousedown.prevent @click="control?.focus()">focus()</HuiButton>
<HuiButton @mousedown.prevent @click="control?.blur()">blur()</HuiButton>
</HuiSpace>
<HuiUpload ref="control" :auto-upload="false" @focus="event = 'focus'" @blur="event = 'blur'" />
<span>{{ event }}</span>
</HuiSpace>
</template>
| Method | Signature |
|---|---|
| focus | () => void |
| blur | () => void |
Whole-Component Focus Events
| Event | Parameters | Behavior |
|---|---|---|
| focus | event: FocusEvent | Once when focus enters from outside the group |
| blur | event: FocusEvent | Once when focus leaves the group; not repeated for internal movement |