File Input
选择、拖放或粘贴文件,校验它们,并随表单一起提交。
文件输入框保存用户选择、拖放或粘贴的文件,按你的规则校验它们,并随表单一起提交。把文件上传到服务器则由你的应用负责。
<script setup lang="ts">
import { FileIcon, UploadIcon, XIcon } from "@lucide/vue"
import {
FileInput,
FileInputDropzone,
FileInputItem,
FileInputItemRemove,
FileInputList,
FileInputTrigger,
formatFileSize,
} from "@ui-sdk/vue/file-input"
</script>
<template>
<FileInput multiple>
<FileInputDropzone>
<UploadIcon aria-hidden="true" />
<p>Drag and drop files here</p>
<p data-slot="hint">Or paste them from your clipboard.</p>
<FileInputTrigger>Browse Files</FileInputTrigger>
</FileInputDropzone>
<FileInputList aria-label="Files">
<FileInputItem v-slot="{ state }">
<FileIcon aria-hidden="true" />
<span>{{ state.file.name }}</span>
<span data-slot="hint">{{ formatFileSize(state.file.size) }}</span>
<FileInputItemRemove>
<XIcon aria-hidden="true" />
</FileInputItemRemove>
</FileInputItem>
</FileInputList>
</FileInput>
</template>安装
npm install @ui-sdk/vue @ui-sdk/core组合
用下面的组合构建 FileInput:
FileInput
├── FileInputTrigger
├── FileInputDropzone
└── FileInputList
└── FileInputItem
└── FileInputItemRemove触发器打开系统的文件选择器。拖放区域接收拖放到它上面的文件,或焦点在它内部时粘贴的文件;请为使用键盘的人保留一个放在它旁边的触发器。列表为每个文件渲染一次它的条目,条目的插槽状态里有 file 和 index。移除按钮移除它所在条目的文件。
用法
导入部件并把它们组合起来:
<script setup lang="ts">
import { XIcon } from "@lucide/vue"
import {
FileInput,
FileInputDropzone,
FileInputItem,
FileInputItemRemove,
FileInputList,
FileInputTrigger,
formatFileSize,
} from "@ui-sdk/vue/file-input"
</script>
<template>
<FileInput name="attachments" multiple>
<FileInputDropzone>
<p>Drag and drop files here</p>
<FileInputTrigger>Browse Files</FileInputTrigger>
</FileInputDropzone>
<FileInputList aria-label="Files">
<FileInputItem v-slot="{ state }">
<span>{{ state.file.name }}</span>
<span>{{ formatFileSize(state.file.size) }}</span>
<FileInputItemRemove>
<XIcon aria-hidden="true" />
</FileInputItemRemove>
</FileInputItem>
</FileInputList>
</FileInput>
</template>上传按钮
只需要系统的文件选择器时,一个触发器就够了。从根部件的插槽状态里读取选中的文件,在按钮旁边显示它的名称。
<FileInput v-slot="{ state }" name="resume">
<FileInputTrigger>Upload Resume</FileInputTrigger>
<span>{{ state.value[0]?.name ?? "No file chosen" }}</span>
</FileInput>接受的文件类型
accept 接受 MIME 类型、通配符和扩展名,比如 image/* 和 .pdf。它会检查来自选择器、拖放和粘贴的文件。扩展名按文件名匹配,即使操作系统报告的 MIME 类型不符合预期。
被拒绝的文件不会加入值。@reject 会收到每个被拒绝的文件及其 reasons,比如 file-type,这样你就能说明它为什么被排除。当文件被拖到拖放区域上方时,data-drag-reject 会表示它们的类型不会被接受。
<FileInput multiple :accept="['image/*', '.pdf']" @reject="(next) => (rejected = next)">限制
用 max-files 限制总数,用 min-size 或 max-size 限制每个文件的字节数。文件太多时,组件会接受通过其他检查的前几个,直到列表装满,并用 too-many-files 拒绝其余的。
<FileInput multiple :max-files="3" :min-size="1" :max-size="5_000_000">单个文件
没有 multiple 时,新文件会替换当前文件。被拒绝的文件不会改变当前值。有 multiple 时,被接受的文件会加入列表。
<FileInput v-slot="{ state }" accept=".pdf">
<FileInputTrigger>{{ state.value[0] ? "Replace PDF" : "Choose a PDF" }}</FileInputTrigger>
</FileInput>校验
加上 validate 来做你自己的检查。返回原因字符串来拒绝文件,返回 null 来接受它。它的第二个参数的 accepted 保存同一次拖放中在这个文件之前已被接受的文件,因此重复检查能发现一次拖放里两个同名文件。它在内置的类型和大小检查之后运行,它的原因会和那些原因一样传给 @reject。在服务器上也要校验上传。
<script setup lang="ts">
const files = createFileInputController()
</script>
<FileInput
multiple
:controller="files"
:validate="(file: File, { accepted }: { accepted: readonly File[] }) => ([...files.getValue(), ...accepted].some((other) => other.name === file.name) ? 'duplicate' : null)"
@reject="(next) => (rejected = next)"
>文件列表
列表只有一个 Tab 停靠点。方向键、Home 和 End 在文件之间移动;Delete 或 Backspace 移除获得焦点的文件。移除按钮以它对应的文件命名,并且不在 Tab 顺序里。
要显示图片预览,为文件创建对象 URL,并在条目消失时撤销它:
<FileInputItem v-slot="{ state }">
<Preview :file="state.file" />
<span>{{ state.file.name }}</span>
<FileInputItemRemove>
<XIcon aria-hidden="true" />
</FileInputItemRemove>
</FileInputItem><!-- Preview.vue -->
<script setup lang="ts">
import { ref, watchEffect } from "vue"
const props = defineProps<{ file: File }>()
const url = ref<string>()
watchEffect((onCleanup) => {
const next = URL.createObjectURL(props.file)
url.value = next
onCleanup(() => URL.revokeObjectURL(next))
})
</script>
<template>
<img v-if="url" :src="url" alt="" />
</template>附件
把文本域放进拖放区域,把文件附加到消息上。paste-target 也会接收从文本域粘贴的文件;粘贴文字仍然保持正常行为。它也可以是另一个元素、CSS 选择器或 "document"。
<script setup lang="ts">
const message = ref<HTMLTextAreaElement | null>(null)
</script>
<template>
<FileInput multiple>
<FileInputDropzone :paste-target="() => message">
<FileInputList aria-label="Attachments">
<FileInputItem v-slot="{ state }">{{ state.file.name }}</FileInputItem>
</FileInputList>
<textarea ref="message" aria-label="Message" />
<FileInputTrigger aria-label="Attach Files">
<PlusIcon aria-hidden="true" />
</FileInputTrigger>
</FileInputDropzone>
</FileInput>
</template>全页拖放
设置 target="document" 来接收页面上任意位置拖放的文件。当文件拖到窗口内时,区域会显示 data-dragging,所以它可以作为全页浮层。拖放到另一个区域的文件仍归那个区域。
<script setup lang="ts">
import { FileIcon, UploadIcon, XIcon } from "@lucide/vue"
import {
FileInput,
FileInputDropzone,
FileInputItem,
FileInputItemRemove,
FileInputList,
FileInputTrigger,
formatFileSize,
} from "@ui-sdk/vue/file-input"
</script>
<template>
<FileInput multiple>
<div data-slot="row">
<p data-slot="hint">Drop files anywhere.</p>
<FileInputTrigger>Upload Files</FileInputTrigger>
</div>
<FileInputDropzone target="document" data-variant="overlay">
<div data-slot="stack">
<UploadIcon aria-hidden="true" />
<p>Drop to attach</p>
</div>
</FileInputDropzone>
<FileInputList aria-label="Attachments">
<FileInputItem v-slot="{ state }">
<FileIcon aria-hidden="true" />
<span>{{ state.file.name }}</span>
<span data-slot="hint">{{ formatFileSize(state.file.size) }}</span>
<FileInputItemRemove>
<XIcon aria-hidden="true" />
</FileInputItemRemove>
</FileInputItem>
</FileInputList>
</FileInput>
</template>拖放区域挂载期间,把文件拖放到所有区域之外不会让页面跳转。拖放到原生文件输入框和普通的文字拖放仍保持它们的行为。
文件夹
directory 选择整个文件夹,并打开 multiple。拖放的文件夹会被递归读取,最多 1,000 个文件,跳过 .DS_Store 这类系统文件。relativePath(file) 返回文件夹内的路径。
<FileInput directory>
<FileInputTrigger>Choose a Folder</FileInputTrigger>
<FileInputList aria-label="Files">
<FileInputItem v-slot="{ state }">{{ relativePath(state.file) }}</FileInputItem>
</FileInputList>
</FileInput>相机
用 capture="environment" 请求后置相机,用 "user" 请求前置相机。提供的选择器取决于设备和浏览器;桌面浏览器会打开文件选择器。
<FileInput accept="image/*" capture="environment">
<FileInputTrigger>Take a Photo</FileInputTrigger>
</FileInput>受控
传入 value,并在 @value-change 里更新它,或用 v-model:value 绑定它。details 里有 reason,以及 added、removed 和 rejected 文件。调用 details.cancel() 保留当前值。即使没有文件被接受,@reject 也会报告被拒绝的文件。
<script setup lang="ts">
const files = ref<File[]>([])
</script>
<FileInput multiple :value="files" @value-change="(value) => (files = value)">从任意位置打开
用 createFileInputController() 创建控制器,并传给 FileInput。用它打开选择器、添加或移除文件、清空值,或读取文件。从用户动作里打开选择器,比如按压按钮,这样浏览器才会允许。文件输入框之外的 FileInputTrigger 通过同一个 controller prop 连接。
<script setup lang="ts">
const attachments = createFileInputController()
</script>
<template>
<button type="button" @click="attachments.open()">Choose Files</button>
<button type="button" @click="attachments.clear()">Clear</button>
<FileInput multiple :controller="attachments" />
</template>播报
组件通过礼貌的实时区域(polite live region)播报被接受、被移除和被拒绝的文件。用 announcement 修改消息,或返回 null 跳过它。
<FileInput
multiple
:announcement="
({ added, removed }) =>
added.length
? `Added ${added.map((file) => file.name).join(', ')}.`
: removed.length
? `Removed ${removed.map((file) => file.name).join(', ')}.`
: null
"
>表单
有了 name,组件会通过原生文件输入框提交它的文件,这个输入框在水合之前就能提交。表单重置会回到 default-value。form 把文件输入框连接到页面上别处的表单。被拒绝的文件永远不会提交,disabled 既会让值不参与提交,也会阻止选择、拖放和粘贴。
<form method="post" enctype="multipart/form-data">
<FileInput name="attachments" multiple :default-value="[coverLetter]">
<FileInputTrigger>Attach Files</FileInputTrigger>
</FileInput>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</form>字段
把文件输入框包进 Field,连接它的标签、描述和校验消息。触发器会成为字段的控件,按压标签会打开选择器。required 在没有文件时阻止表单提交。
<Field>
<FieldLabel>Proof of address</FieldLabel>
<FileInput name="proof" required :accept="['image/*', '.pdf']">
<FileInputTrigger>Choose a File</FileInputTrigger>
</FileInput>
<FieldDescription>A utility bill or bank statement from the last 3 months.</FieldDescription>
<FieldError match="valueMissing">Add a scan to continue.</FieldError>
</Field>自定义渲染
每个部件都接受 render 插槽,用来在原地渲染不同的元素。它会收到要绑定的 props 和部件的状态。根部件、拖放区域和条目的默认插槽也会通过 v-slot="{ state }" 收到部件的状态:
<FileInputDropzone>
<template #render="{ props, state }">
<section v-bind="props" aria-label="Gallery upload">
{{ state.dragReject ? "Images only" : state.dragAccept ? "Release to add" : "Drag images here" }}
</section>
</template>
</FileInputDropzone>
<FileInputList aria-label="Images">
<template #render="{ props, children }">
<ul v-bind="props">
<component :is="children" />
</ul>
</template>
<FileInputItem>
<template #render="{ props, state }">
<li v-bind="props">{{ state.index + 1 }}. {{ state.file.name }}</li>
</template>
</FileInputItem>
</FileInputList>关于 render 的更多内容,见部件与组合。
样式
在拖放区域上使用 data-dragging、data-drag-accept 和 data-drag-reject,显示拖放会有什么效果。是否接受拖放取决于浏览器在放下文件之前给出的文件信息。在 Field 内部,触发器还会得到字段的属性,比如 data-invalid。
每个部件都有一个 data-slot,比如 file-input-dropzone,它的状态属性列在数据属性下。
数据属性
FileInput
[data-slot="file-input"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-required | Present when a file is required. |
data-dragging | Present while files are dragged over one of its drop zones. |
FileInputTrigger
[data-slot="file-input-trigger"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-required | Present when a file is required. |
FileInputDropzone
[data-slot="file-input-dropzone"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-dragging | Present while files are dragged over the zone, or the window with target="document". |
data-drag-accept | Present while dragged files look acceptable, from their types and count. |
data-drag-reject | Present while a dragged file has a type accept rules out, or there are too many. |
FileInputList
[data-slot="file-input-list"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-required | Present when a file is required. |
FileInputItem
[data-slot="file-input-item"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
FileInputItemRemove
[data-slot="file-input-item-remove"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
API 参考
Props 与下面相同。onValueChange 是 @value-change 和 v-model:value,onReject 是 @reject。
FileInput
accept?string | readonly string[]- The files to accept, like the
acceptattribute: MIME types ("image/png"), wildcards ("image/*") and extensions (".pdf"), in a comma-separated string or an array. Without it, any file. maxFiles?number- The most files accepted at a time. The first ones that pass the other checks are accepted, and the rest are rejected.
maxSize?number- The largest size accepted, in bytes.
minSize?number- The smallest size accepted, in bytes.
validate?((file: File, batch: { accepted: readonly File[]; }) => string | null | undefined | void)- A check of your own. Return a reason, like
"duplicate", to reject the file, or nothing to accept it.acceptedholds the files of the same choice, drop or paste accepted before this one. value?File[]- The files, to control the file input.
defaultValue?File[]- The files at first, when uncontrolled. A form reset returns to them.
@value-change((value: File[], details: FileInputValueChangeDetails) => void)- Runs when files are added or removed, with what changed in the details.
details.cancel()stops it. @reject((rejected: FileRejection[], details: CommitDetails<FileInputValueChangeReason>) => void)- Runs when files fail the checks, after
@value-change, with every reason each failed, even when none were accepted. multiple?boolean- Holds more than one file. New files join the ones it has, up to
maxFilesin all. Without it, a new file replaces the one it has. directory?boolean- Picks a whole folder, with every file inside it. Turns on
multiple. capture?"environment" | "user" | boolean- Opens the camera on phones instead of the files:
"user"for the front camera,"environment"for the back one, ortruefor the default one. name?string- The name the files submit under. Without one, nothing is submitted.
form?string- The id of a form to belong to, when it isn't inside that form.
required?boolean- Blocks form submission until it holds a file, with the browser's own message.
disabled?boolean- Disables it like a native control: the trigger can't be focused or used, drops and pastes are ignored, and nothing is submitted.
announcement?((change: FileInputChange) => string | null | undefined)- What screen readers hear after a change. Return null for nothing.
controller?object- Adds and removes files from anywhere. Create one with
createFileInputController(). debug?boolean- Logs every state change with its reason to the console, in development builds.
FileInputTrigger
controller?object- Connects a trigger outside the file input, like one in a toolbar, to the file input with this controller.
FileInputDropzone
target?FileInputDropzoneTarget- Where it takes drops.
"document"takes files dropped anywhere on the page, and the zone showsdata-draggingwhile files are over the window, so it can be a full-page overlay. pasteTarget?FileInputPasteTarget- Somewhere else to take pasted files from, on top of pastes while focus is inside the zone:
"document", an element, a CSS selector, or a function that returns an element, like a prompt's text area. Text pastes are left alone.
FileInputList
为每个文件渲染一次它的默认插槽。
FileInputItem
fileFile- The file this item shows. The list passes it to the items it renders.
FileInputItemRemove
移除它所在条目的文件。它以对应的文件命名,并且不在 Tab 顺序里。
状态
根部件、触发器和列表的状态:
valuereadonly File[]- The files it holds.
disabledboolean- Whether it's disabled, by itself or by a
<fieldset>. requiredboolean- Whether a form won't submit while it holds no files.
draggingboolean- Whether files are being dragged over one of its drop zones.
拖放区域的状态:
draggingboolean- Whether files are being dragged over it, or over the page for a page-wide zone.
dragAcceptboolean- Whether the dragged files look acceptable, from their types and count.
dragRejectboolean- Whether a dragged file has a type
acceptrules out, or there are too many. disabledboolean- Whether the file input is disabled, by itself or by a
<fieldset>, so drops and pastes are ignored.
条目的状态:
fileFile- The file this item shows: the one its
FileInputListrenders it for, or itsfileprop. indexnumber- Where it is in the value, from 0.
disabledboolean- Whether the file input is disabled, so the item can't be removed.
移除按钮的状态:
disabledboolean- Whether the file input is disabled, so the button can't remove its file.
原因
pickerEvent- Files were chosen in the system's file picker. Its input's
changeevent. dropDragEvent- Files were dropped on a drop zone, or text and tokens on a token input.
pasteClipboardEvent- Files were pasted, like a screenshot, or text and tokens into a token input.
remove-pressMouseEvent | KeyboardEvent- A chip's remove part was pressed, or Backspace or Delete removed a chip or a span.
resetnone- A form reset.
imperativenone- A controller or
apicall.
被拒绝的文件会带有一个或多个这样的原因,或来自你的 validate 的原因:file-type、file-too-large、file-too-small 和 too-many-files。
控制器
用 createFileInputController() 创建一个,并作为 controller 传入。
getValue()() => readonly File[]- The files it holds.
setValue(files, options?)(files: readonly File[], options?: FileInputChangeOptions | undefined) => boolean- Replaces the files, without checking them. Returns false when canceled.
addFiles(files, options?)(files: readonly File[] | FileList, options?: FileInputChangeOptions | undefined) => boolean- Runs files through the checks and adds the accepted ones, like a drop. Returns false when disabled or canceled.
removeFile(file, options?)(file: File, options?: FileInputChangeOptions | undefined) => boolean- Removes one file. Returns false when it isn't there, or the change is canceled.
clear(options?)(options?: FileInputChangeOptions | undefined) => boolean- Removes every file.
open()() => boolean- Opens the file picker. Browsers only allow it during a user action, like a click. Returns false when disabled.
focus()() => void- Moves focus to the trigger.
isDragging()() => boolean- Whether files are being dragged over a drop zone.
无障碍
为使用键盘或屏幕阅读器的人保留一个放在拖放区域旁边的触发器。变更会通过礼貌的实时区域播报,文件列表支持键盘导航和移除。
- Dropped files are reported, the rejected ones with every reason.
- Files over the zone show data-dragging and data-drag-accept until they leave.
- A type the file input doesn't accept shows data-drag-reject.
- More files than the file input takes show data-drag-reject.
- The drag state holds while the drag crosses the zone's children.
- Text dragged over the zone is ignored.
- A drag that started in the page is ignored, even with files.
- The first files up to maxFiles are accepted and the rest rejected.
- MaxFiles counts the files the file input already holds.
- Without multiple, the first file is accepted, and a new one replaces it.
- A disabled file input takes no drops and shows no drag state.
- Files dropped outside the zone don't open in the browser.
- Pasting files while focus is inside the zone reports them.
- Pasting text is left alone.
- Pasting files into the paste target reports them.
- A page-wide zone shows while files are over the window.
- A page-wide zone takes files dropped anywhere.
- A drop on a zone doesn't reach a page-wide zone.
- Render functions get the drag state. 仅在 React 和 Vue 运行。
- A trigger alone opens the file picker, and the chosen file is reported.
- Files the accept list rules out are rejected.
- An unnamed file input empties its input after each choice, so the same file can be chosen again.
- A folder picker reports every file inside the folder.
- The input carries accept, capture, multiple and directory.
- The input stays out of the tab order and the accessibility tree.
- With multiple, chosen files join the ones dropped before.
- A named file input submits the chosen files with its form.
- Rejected files are never submitted.
- A named file input with no files submits an empty file, like a native input.
- Files dropped on the zone go in the form.
- Canceling a change keeps its files out of the form.
- A form reset clears the files.
- A required file input blocks submission and shows the field's error.
- Files set from script update the field even when the announcement throws. 仅在 Web components 运行。
- The field's label and the button's text name the trigger, and its description describes it.
- A press on the field's label opens the picker.
- A disabled file input disables its trigger.
运行于 React、Vue 和 web components。
- Each file shows as an item in the list, in order.
- A remove button is named after its file, and removes it.
- The list is one tab stop, and arrow keys, Home and End move between items.
- Backspace on a focused item removes it and focuses the next one.
- A removal is announced politely.
- A canceled change leaves the list as it was.
- A form reset empties the list.
- A controlled file input shows the value it's given. 仅在 React 和 Vue 运行。
- A removal a controlled owner ignores keeps the item and its focus. 仅在 React 和 Vue 运行。
- The value property sets the files quietly on web components, and the api reports. 仅在 Web components 运行。
- The remove buttons are out of the tab order.
运行于 React、Vue 和 web components。
- No axe violations at first.
- No axe violations while dragging.
- No axe violations with files in the list.
- No axe violations with the field's error showing.
- No axe violations when disabled.
- The zone isn't a control: the trigger inside it is the one tab stop.
- The accessibility tree is the same everywhere.
- Accepted and rejected counts are announced politely.
- A choice from the picker is announced too.
运行于 React、Vue 和 web components。