forge42dev / remix-hook-form

Open source wrapper for react-hook-form aimed at Remix.run
MIT License
330 stars 27 forks source link

Could not parse content as FormData #65

Closed ronkristoff closed 8 months ago

ronkristoff commented 8 months ago

i'm trying to make a form with file upload but i can't make it work using remix hook form, i am getting an error "Could not parse content as FormData".

<Form onSubmit={handleSubmit} method="POST" encType="multipart/form-data">
      <div>
        <Label htmlFor="title">
          Title:
          <Input type="text" {...register("title")} />
          {errors.title && errors.title.message && (
            <ErrorMessage message={errors.title.message} />
          )}
        </Label>
      </div>
      <div>
        <Label htmlFor="content">
          Content:
          <Input type="text" {...register("content")} />
          {errors.content && errors.content.message && (
            <ErrorMessage message={errors.content.message} />
          )}
        </Label>
      </div>
      <div>
        <Label htmlFor="file-upload">
          Choose file:
          <Input
            type="file"
            id="file-upload"
            accept="image/*"
            {...register("image")}
          />
          {errors.image && errors.image.message && (
            <ErrorMessage message={errors.image.message} />
          )}
        </Label>
      </div>

      <Button variant={"default"} className="mt-4 w-full">
        Add
      </Button>
    </Form>
export const action = async ({ request, params }: ActionFunctionArgs) => {
  const imageFile = await unstable_parseMultipartFormData(
    request,
    fileUploadHandler()
  );

  console.log("imageFile", imageFile);

  let { data, errors, receivedValues } = await getValidatedFormData<FormData>(
    request,
    resolver
  );

  console.log("receivedValues", receivedValues);
  console.log("data", data);
const schema = z.object({
  title: z.string().min(2).max(300),
  content: z.string().min(1).max(200),
  image: z.any().refine((files) => files?.length == 1, "Image is required."),
});
ronkristoff commented 8 months ago

After trying a couple of times, i figured out that the payload for the image was not binary even though i already set the encType to multipart form data , i looked at the example again and saw that there was a "submitConfig" that i need to set the encType also. After trying it out this is now working. It's just weird that the encType in the

element was not being recognized.