2
votes

I have a problem. I want to upload an image and a variable to my webpage, so I created this code:

using (var formContent = new MultipartFormDataContent("NKdKd9Yk"))
{
    formContent.Headers.ContentType.MediaType = "multipart/form-data";

    StringContent UserIdContent = new StringContent(App.User.Id.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
    formContent.Add(UserIdContent, "id");

    StringContent CreatedImageContent = new StringContent(CreatedImage, Encoding.UTF8, "binary/octet-streOpenWriteam");
    formContent.Add(CreatedImageContent , "image");

    using (var client = new HttpClient())
    {
        try
        {
            // 4.. Execute the MultipartPostMethod
            var message = await client.PostAsync(url, formContent);
            // 5.a Receive the response
            var result = await message.Content.ReadAsStringAsync();

            if (result == "Success")
            {
                App.Current.MainPage = new SideMenuItems();
            }
        }
        catch (Exception ex)
        {
            // Do what you want if it fails.
            throw ex;
        }
    }
}

Now both the variables are getting received by the server, but the image variable is the path of the image on the device and not the image itself.

What am I doing wrong?

1

1 Answers

1
votes

Use the path to get a stream of the image and use stream content.

using (var formContent = new MultipartFormDataContent("NKdKd9Yk")) {
    formContent.Headers.ContentType.MediaType = "multipart/form-data";

    var id = App.User.Id.ToString();
    StringContent UserIdContent = new StringContent(id, Encoding.UTF8, "application/x-www-form-urlencoded");
    formContent.Add(UserIdContent, "id");

    FileStream fs = System.IO.File.OpenRead(CreatedImage);
    formContent.Add(new StreamContent(fs), "image");

    using (var client = new HttpClient()) {
        try {
            // 4.. Execute the MultipartPostMethod
            var message = await client.PostAsync(url, formContent);
            // 5.a Receive the response
            var result = await message.Content.ReadAsStringAsync();

            if (result == "Success") {
                App.Current.MainPage = new SideMenuItems();
            }
        } catch (Exception ex) {
            // Do what you want if it fails.
            throw ex;
        }
    }
}