2

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?

0

1 Answer 1

1

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.