javascript - 在 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)
}
解决方案
根据 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
帮助程序,从这里开始,剩下的就是试验和错误。
推荐阅读
- python - Python kivy (kivyMD) 如何获取 MDDropdownMenu 的值
- jquery - 通过 $.each Jquery 获取数据 JsonArray 和 JsonObject
- c# - 带有 XML 文件的身份验证表单
- actionscript-3 - Flex 项目的 IntelliJ IDEA 错误 1172
- vba - 如何使用 Excel VBA 将工作簿中的数据导入用户表单组合框和文本框?
- c# - Linq 或 lambda 选择所有字段修改一个
- android - 在调试时保持应用程序处于活动状态
- ltrace - 如何让 ltrace -S 显示系统调用的所有参数?
- sql - 动态 sql 数据透视值出现在单独的列中
- c++ - 无法使用 qt 在 imx6 中发送 spi 消息