示例说明
FormData 的值是字符串与 File 的混合体,直接取用等于裸奔。把 entries 先归一化为普通对象——跳过浏览器空文件占位——再交给 Zod:z.instanceof(File) 验证真文件,refine 链分别约束体积与类型,文本字段独立校验。全部通过后才 arrayBuffer 读取内容,坏文件一个字节都不会进入存储层。
技术要点
- instanceof 守卫确保真是文件对象
- refine 链逐条给出可读错误
- 校验通过后才读取文件内容
代码解读
handleAvatarForm 循环表单项跳过空名零字节的占位文件;safeParse 失败返回带字段定位的问题清单。成功分支才把头像转成字节并持久化,display 名称与同意标志各自受长度与字面量约束。返回值判别联合让调用方分支明确。
使用建议
MIME 可被客户端伪造,安全场景校验文件魔数。多文件字段用数组 schema 批量校验。持久化命名由服务端生成,不信任客户端文件名。
代码示例
import { z } from 'zod';
const MAX_FILE_BYTES = 5 * 1024 * 1024;
const FileSchema = z.instanceof(File)
.refine((f) => f.size <= MAX_FILE_BYTES, {
message: 'file exceeds 5MB limit',
})
.refine(
(f) => ['image/png', 'image/jpeg'].includes(f.type),
{ message: 'only png or jpeg accepted' },
);
const UploadSchema = z.object({
avatar: FileSchema,
displayName: z.string().min(2).max(40),
consent: z.literal('on'),
});
type UploadInput = z.infer<typeof UploadSchema>;
async function handleAvatarForm(form: FormData) {
const raw: Record<string, unknown> = {};
for (const [key, value] of form.entries()) {
if (value instanceof File && value.size === 0 && value.name === '') {
continue;
}
raw[key] = value;
}
const parsed = UploadSchema.safeParse(raw);
if (!parsed.success) {
return {
ok: false as const,
issues: parsed.error.issues.map((i) => ({
field: i.path.join('.'),
message: i.message,
})),
};
}
const input: UploadInput = parsed.data;
const bytes = new Uint8Array(await input.avatar.arrayBuffer());
await persistAvatar(input.displayName, bytes);
return { ok: true as const, name: input.avatar.name, size: bytes.length };
}
async function persistAvatar(_name: string, _bytes: Uint8Array) {
console.log('persisting avatar');
}