Search code examples
c#resthttpwebrequest

C# Get Request Directus


recently i discovered this amazing cms called Directus, where you can manage your database and Tables with web request and Json. Everything worked fine creating,updating,reading...till i came to the point where i want to Create (Upload) a Image using WebRequest.

Im basicly reading a image as Base64 and writing the data along with the parameters in the Uri using a simple GET request exactly like described in API.

Regardless what i try and use the Images Never show up in my Files. Am i doing something wrong or forgetting something?

Or does directus want something else from me?

My first try:

public static async void UploadUserImage() {

            var uri = "http://IP/Directus/api/1/files?access_token=SecretApiKey";
            var data = GetImageData();
            var finalUri = $"{uri}&data={data}";

            using (var client = new HttpClient()) {
                var responseString = await client.GetStringAsync(finalUri);
                Console.Write(responseString);
            }
        }

My Second try with Json:

public static async void UploadUserImage() {

            var uri = "http://IP/Directus/api/1/files?access_token=SecretApiKey";
            var data = GetImageData();
            var finalUri = $"{uri}&data={data}";

            var postModel = new PictureModel {
                data = data,
                title = "Test",
                name = "test"
            };


        using (var client = new HttpClient())
            {
                // Serialize our concrete class into a JSON String
                var content = JsonConvert.SerializeObject(postModel);
                var contenta = new StringContent(content, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(finalUri, contenta);
                var result = await response.Content.ReadAsByteArrayAsync();
                Console.Write(System.Text.Encoding.UTF8.GetString(result));
            }
        }

Solution

  • The docs is incorrect it's actually a POST request. Thanks for pointing that out.

    To upload a new file you need three provide three values:

    {
        "name": "image.png",
        "type": "image/png",
        "data": "base64content"
    }
    

    The data content has to be in this format data:<mime-type>;base64,<data-content> so it will look something like this: data:image/png;base64,ThisIsABase64Content

    We are updating the docs and removing the data:image/png which is unnecessary.