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

1 messages · Page 1 of 1 (latest)

wide saddle
#

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.

vagrant kindleBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)