javarestbase64contentfulcontentful-management

Trying to upload image to VIA Contentful Content Management API JAVA


I'm trying to upload an image via content management API. What I want to achieve is: Upload the image to the predefined Image content model and fetch the url later via the Content Delivery API - basically I wish to use Contentful as my own image server storage.

Is there any way to send the image as a base64 string/byte array? The media object type the CMA expects is not very clear to me and I've tried sending an image as a byte array but it complains that "Links must be Objects and not Arrays" . Here is what I have so far:

public static void createImageEntity(byte[] imageAsBase64, String name) {

    // Create the client with given acces token
    final CMAClient client = new CMAClient
                    .Builder()
                    .setAccessToken(CDA_TOKEN)
                    .build();

    // Create new entry for given client
    final CMAEntry entry = new CMAEntry()
                    .setId(name + "-id")
                    .setField("title", name, "en-US")
                    .setField("photo", imageAsBase64, "en-US");


    final CMAEntry createdEntry = client
            .entries()
            .create(SPACE_ID, IMAGE_CONTENT_TYPE_ID, entry);
}

Solution

  • You can't set a field directly to a byte array as you're doing here. You first need to upload the binary file to Contentful, then wrap that in an Asset and then reference that asset from your entry field.

    In Java you basically create an upload like this:

    final CMAUpload upload =
    client
        .uploads()
        .create("<space_id>",
            // this stream should point to your file to be uploaded.
            new FileInputStream("your file")
        );
    

    Note that uploading binary files like this is still a fairly new feature and is considered in beta. You can read more about it in this blog post: https://www.contentful.com/blog/2017/03/02/uploading-files-directly-to-contentful/