首页 > 解决方案 > 在 DatoCMS 中创建记录时如何包含图像

问题描述

我的应用程序通过 javascript 客户端成功提交单行文本,如下所示。我不明白如何实际发送图像数据。单个资产的接受字段似乎没有提及实际的图像数据。

看起来需要多个 http 请求才能完成此操作,但再一次,我的文件输入数据到哪里去了?

- - 更新 - -

看起来必须先上传图像才能获取 ID,该 ID 在创建新记录时使用。您不能同时上传图像和文本。

我目前收到此错误: 在此处输入图像描述

参考:DatoCMS - 将图片添加到新记录 Uploadng assets

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


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)


}

标签: javascriptgraphqlgatsby

解决方案


根据 DatoCMS 文档,我认为您的createRecord函数应如下所示:

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)

  // here you are creating the path for local image
  const path = await client.createUploadPath(profileImage); 

  // you can then use the returned path to create a new upload:
  const upload = await client.uploads.create({ path });

  const record = await client.items.create({
    itemType: "679748",
    path, // alternatively use upload
    firstName,
    lastName,
    email,
    slug
  })
  return record
}

文档在资产需要如何构建方面不够清楚,您可能需要:

  const record = await client.items.create({
    itemType: "679748",
    profileImage: {
      // in this case we're just passing the upload ID, as the
      // asset's defaults for alt, title, etc. are fine:
      uploadId: upload.id,
    },
    firstName,
    lastName,
    email,
    slug
  })

答案与您的内容模型严格相关,但基于在节点中创建上传并将图片添加到记录,但在这两种情况下您都缺少createUploadPath帮助程序,从这里开始,剩下的就是试验和错误。


推荐阅读