Next.js Discord

Discord Forum

Uploading files/images to a database with server actions and Zod

Unanswered
Charmantle posted this in #help-forum
Open in Discord
Hi, I am having a lot of trouble figuring out how to upload images with a useActionState form to my Supabase storage bucket. I'm using Zod to validate the image type, as shown below:
export const EditProfileFormSchema = z
    .object({
        picture: z
            .instanceof(File) // import { File } from "buffer"
            .optional()
            .refine((file) => (!file || file.size <= MAX_FILE_SIZE)!, { message: "Max file size is 6MB" })
            .refine((file) => (!file || ACCEPTED_IMAGE_TYPES.includes(file.type))!, { message: "File type not supported" }),
        // More validation for other fields blow

The main problem arises in my server action code when I try to call the get() function on my form data.
const validatedFields = EditProfileFormSchema.safeParse({
        picture: formData.get("picture"), // error is thrown whenever this line is uncommented
        displayName: formData.get("displayName"),
        bio: formData.get("bio"),
        role: formData.get("role"),
    })

    if (!validatedFields.success) {
        return {
            errors: validatedFields.error.flatten().fieldErrors,
        }
    }

In my form code I have correctly put the name attributes as the form field names. Below is an example of my file input element:
<div className="space-y-1">
        <Label htmlFor="picture">Profile Picture</Label>
        <Input id="picture" name="picture" type="file" className="justify-center items-center" />
        {state?.errors.picture && <p className="text-sm text-destructive">{state.errors.picture}</p>}
</div>

The picture I have attached shows the error that I get whenever I try to submit the form. My guess is that my Zod validation is incorrect, which is whats causing the error.

1 Reply