Upload image with new record from Node Client

My app currently creates a new record containing name and email.

I’d like to include an image at the same time, but I have not found how to do this exactly.

I already have the field set up on the model in Dato.

This article still does not show how to send the form data

const { SiteClient } = require("datocms-client")
const client = new SiteClient("API_KEY")
export default async function createRecord({ firstName, lastName, email, profileImage, slug}) {
    console.log('@createProfile',profileImage)
  const record = await client.items.create({
    itemType: "679748",
    profileImage,
    firstName,
    lastName,
    email,
    slug
  })
  return record
}

Hi @zacharydurland

it’s a two step process:

  • you upload a file (and you get an upload ID)
  • you create a record, passing the upload ID to the single asset field api key

Uploading an image to DatoCMS

Here you can read how to upload a file to DatoCMS using a remote URL or path to a local file. You’ll get an upload object as result.

Creating a record with a single asset field

Here you can read how to create a record and, if you scroll down, you’ll see the payload needed for a single asset field

So, you have to pass an object where upload_id is equal to the upload object ID that the previous call returned. You can even customize alt/title for this specific record image, if you want.

Hope this helps!

@faber Thank you for your help! I’ve made progress, but I am encountering an error at the time of creating the file upload and passing in the file.

I am passing in e.target.file[0], essentially.

Error:
Screen Shot 2021-04-15 at 11.20.13 AM

Current Code:

const { SiteClient } = require("datocms-client")
const client = new SiteClient("TOKEN")


export default async function createProfile({ firstName, lastName, email, profileImage, slug}) {

  console.log("@createUpload", profileImage)

  async function createUpload(profileImage) {
    const path = await client.createUploadPath(profileImage);
    const upload = await client.uploads.create({
      path,
      author: `${firstName} ${lastName}`,
      copyright: "2021",
      defaultFieldMetadata: {
        en: {
          alt: profileImage.name,
          title: profileImage.name,
          focalPoint: {
            x: 0,
            y: 0,
          },
          customData: {
            watermark: true,
          },
        },
      },
    })

    console.log(upload)

  // this is the next step 
  // const record = await client.items.create({
  //   itemType: "679748",
  //   firstName,
  //   lastName,
  //   email,
  //   slug
  // })

  }

  createUpload(profileImage)


}

Hi @zacharydurland , so you are inside a browser, not inside node. Am I right? Then take a look at this example on how to create a DatoCMS upload instead: Create an upload in the browser.