验证图像输入工作意外... / Nextjs 服务器操作 - Zod

问题描述 投票:0回答:1

我有这样的 zod 验证模式...

export const newProductSchema = z.object({
  title: z.string().min(2, 'Minimum 2 chars.').max(15, 'Maximum 15 chars.'),
  image: z
    .any()
    .refine(
      (files) => files?.[0]?.size <= MAX_FILE_SIZE,
      `Max image size is 5MB.`
    )
    .refine(
      (files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type),
      'Only .jpg, .jpeg, .png and .webp formats are supported.'
    )
    .optional(),
});

但是当我上传一个简单的 png (45kb) 时,它会抛出错误第一个错误“最大图像大小为 5MB”

如果我删除第一个验证,它会抛出第二个验证错误“仅支持 .jpg、.jpeg、.png 和 .webp 格式。”

总而言之,它总是返回错误

export const MAX_FILE_SIZE =  1024 * 1024 * 5;
export const ACCEPTED_IMAGE_TYPES = [
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/webp',
];
reactjs next.js zod
1个回答
0
投票

这是我在处理图像验证时总是使用的,最好使用

instanceof(File)
而不是
any()
,以便精炼中的参数
file
是类型安全的

image: z
    .instanceof(File)
    .optional()
    .refine(
      (file) => !file || file.size !== 0 || file.size <= MAX_UPLOAD_SIZE,
      `Max image size is ${MAX_MB}MB`
    )
    .refine(
      (file) =>
        !file || file.type === "" || ACCEPTED_IMAGE_TYPES.includes(file.type),
      "Only .jpg, .jpeg, and .png formats are supported"
    ),
© www.soinside.com 2019 - 2024. All rights reserved.