【问题标题】:Contentful API: upload and assign image to an entryContentful API:上传图像并将其分配给条目
【发布时间】:2020-07-16 20:26:02
【问题描述】:

我一直在使用 Contentful Management Javascript SDK 来更新我的 Contentful 空间中的条目,并且能够更新带有文本的简单字段没有问题。

我的问题是我不知道如何在我的条目中更新 images;我可以将图像上传到媒体部分,但我无法分配任何图像到条目属性。

这是可能的还是 Contentful 的限制?

到目前为止,这是我的代码:

client.getSpace(CONTENTFUL_SPACE).then((space) => {
// retrieve my Contentful space

    space.getEntry(CONTENTFUL_ENTRY).then(function (entry) {
    // get a specific entry

        // create a new asset in my Contentful media section
        space.createAssetWithId(RANDOM_ID, {
            fields: {
                file: {
                    'en-GB': { 
                        contentType: 'image/jpeg',
                        fileName: 'test.jpg',
                        upload: 'http://www.example.com/test.jpg'
                    }
                }
            }
        })
        .then(asset => asset.processForAllLocales())
        .then(asset => asset.publish())
        .then(function(asset) {

            // assign uploaded image as an entry field
            // (none of these work:)
            entry.fields["image"]["en-GB"] = asset.sys.id;
            entry.fields["image"]["en-GB"] = asset.fields.file["en-GB"].url;
            entry.fields["image"]["en-GB"] = asset;
        });
    });
});

【问题讨论】:

    标签: contentful contentful-management


    【解决方案1】:

    您好,我是 js SDK 的维护者,假设您有一个名为 image 的媒体类型字段,您可以如何将资产添加到您的条目中。

    client.getSpace(CONTENTFUL_SPACE).then((space) => {
    // retrieve my Contentful space
    
    space.getEntry(CONTENTFUL_ENTRY).then(function (entry) {
    // get a specific entry
    
        // create a new asset in my Contentful media section
        space.createAssetWithId(RANDOM_ID, {
            fields: {
                file: {
                    'en-GB': { 
                        contentType: 'image/jpeg',
                        fileName: 'test.jpg',
                        upload: 'http://www.example.com/test.jpg'
                    }
                }
            }
        })
        .then(asset => asset.processForAllLocales())
        .then(asset => asset.publish())
        .then(function(asset) {
    
            // assign uploaded image as an entry field
            entry.fields["image"]["en-GB"] = {"sys": {"id": asset.sys.id, "linkType": "Asset", "type": "Link"}};
            return entry.update()
        });
    });
    });
    

    【讨论】:

    • 嗨 Khaled,我想知道在我们能够发布要添加图像的条目之前,我们如何获取条目 ID?
    • 如果条目已创建,您可以将 space.getEntry 替换为 space.createEntry
    • 嗨哈立德。感谢您的答复。我正在尝试添加 entry.update() 但出现版本不匹配错误。我读到我们需要在标题中添加 X-Contentful-Version。我不确定为什么会这样,而这个答案似乎一直适用于 OP。
    猜你喜欢
    • 1970-01-01
    • 2018-08-09
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多