Skip to content

Issue with upload file using Payload CMS REST API #11681

Description

@mrwebninja

Describe the Bug

I am working with playload cms & trying to create a doc in collection with a file, following this payload documentation article https://payloadcms.com/docs/upload/overview#uploading-files

Collection config code

import type { CollectionConfig } from 'payload'
export const DemoCollection: CollectionConfig = {
  slug: 'demoCollection',
  fields: [
    {
      type: 'text',
      name: 'title',
      label: 'Title',
    },
    { type: 'upload', name: 'image', label: 'Image', relationTo: 'media' },
  ],
}

upload Page using REST API

'use client'
const FormSchema = z.object({
  title: z.string().min(2, {
    message: 'Title must be at least 2 characters.',
  }),
  image: z.instanceof(FileList),
})
const DemoPage = () => {
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      title: '',
    },
  })
  async function onSubmit(data: z.infer<typeof FormSchema>) {
    const formData = new FormData()
      formData.append('image', data.image[0])
    formData.append('title', data.title)
    console.log('formData', formData)
    try {
      const req = await fetch('{apiurl}/demoCollection', {
        method: 'POST',
        credentials: 'include',
        body: formData,
      })
      const data = await req.json()
      console.log('res data', data)
    } catch (err) {
      console.log(err)
    }
  }
  return (
    <div className="container">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Title</FormLabel>
                <FormControl>
                  <Input placeholder="Enter title" {...field} />
                </FormControl>
                <FormDescription>This is the title of your demo item.</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="image"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    type="file"
                    onChange={(e) => {
                      field.onChange(e.target.files)
                    }}
                  />
                </FormControl>
                <FormDescription>Upload your image file.</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type="submit">Submit</Button>
        </form>
      </Form>
    </div>
  )
}
export default DemoPage

error on browser
Something went wrong.

error on the server console

Cannot read properties of undefined (reading 'title')

Thanks in advance for your help

Link to the code that reproduces this issue

https://github.com/payloadcms/payload/tree/main/templates/website

Reproduction Steps

I also try with include headers
headers: {

  • 'Content-Type': 'multipart/form-data'
    *}

Which area(s) are affected? (Select all that apply)

Not sure

Environment Info

Node: 22.14.0
Relevant Packages:
  payload: 3.28.1
  next: 15.2.0
  @payloadcms/db-mongodb: 3.25.0
  @payloadcms/email-nodemailer: 3.27.0
  @payloadcms/email-resend: 3.25.0
  @payloadcms/graphql: 3.27.0
  @payloadcms/live-preview: 3.27.0
  @payloadcms/live-preview-react: 3.25.0
  @payloadcms/next/utilities: 3.25.0
  @payloadcms/payload-cloud: 3.25.0
  @payloadcms/plugin-form-builder: 3.25.0
  @payloadcms/plugin-nested-docs: 3.25.0
  @payloadcms/plugin-redirects: 3.25.0
  @payloadcms/plugin-search: 3.25.0
  @payloadcms/plugin-seo: 3.25.0
  @payloadcms/richtext-lexical: 3.25.0
  @payloadcms/translations: 3.27.0
  @payloadcms/ui/shared: 3.25.0
  react: 19.0.0
  react-dom: 19.0.0

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions