I am attempting to upload a file to S3 with a Zod validated form on Next 14.2.2.
I am getting the error: Error: file.arrayBuffer is not a function
.
Form:
const formSchema = z.object({
file: z.any().refine((file) => file?.length > 0, 'File is required.'),
});
export function CreatePhotoForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
});
const fileRef = form.register('file');
async function onSubmit(values: z.infer<typeof formSchema>) {
const formData = new FormData();
formData.append('file', values.file!);
await createPhoto(formData);
}
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-8"
encType="multipart/form-data"
>
<FormField
control={form.control}
name="file"
render={({ field }) => {
return (
<FormItem>
<FormLabel>Photos</FormLabel>
<FormControl>
<Input
type="file"
{...fileRef}
onChange={(event) => {
console.log(event.target?.files);
field.onChange(event.target?.files);
}}
multiple
/>
</FormControl>
<FormMessage />
</FormItem>
);
}}
/>
<Button type="submit" className="self-end">
Submit
</Button>
</form>
</Form>
);
}
Server action:
export async function createPhoto(formData: FormData) {
const files = formData.getAll('file') as File[];
const response = await Promise.all(
files.map(async (file) => {
const body = (await file.arrayBuffer()) as Buffer; // error happening here
const uploadResponse = await awsUpload({ fileName: file.name, body });
console.log({ uploadResponse });
})
);
console.log({ response });
//await photos.createPhoto();
revalidatePath('/photos');
}
Console logging the files
variable in my server action gives me [ '[object FileList]' ]
which seems off. Uploading multiple files also doesn’t increase the size of files
, console logging the length just gives me 1
each time.