2

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);
}
Olaru Vlad
  • 267
  • 1
  • 6
  • 13

1 Answers1

2

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/

Robban
  • 6,729
  • 2
  • 39
  • 47
  • I've read about that, but don't seem to have any uploads() on my CMAClient even though I have the latest versions from mvnrepository. Any idea where I could find that? – Olaru Vlad Apr 09 '17 at 12:57
  • Might be that the Java SDK does not yet support it in the latest stable version. I know it's coming though. Another alternative is to upload your binary file somewhere, like dropbox and then point your newly created asset to this using the standard uploadUrl field. – Robban Apr 09 '17 at 13:07
  • I managed after all to do exactly what I wanted with the dropbox api :) thank you for your tips! – Olaru Vlad Apr 09 '17 at 16:25