Coding Bots
Coding Bots

Reputation: 41

How to send MultipartForm using POST method in (Windows Phone 8.1) C#

Can any one explain how can i make POST request to a URL on web with different type of data, in my case i have an image and two string type values to send to a server in PHP.
here what i already have done

var stream = await file.OpenStreamForReadAsync();
var streamcontent = new StreamContent(stream);
streamcontent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
    Name = "photo",
    FileName = file.Name
};
streamcontent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
MultipartFormDataContent multipart = new MultipartFormDataContent();
multipart.Add(streamcontent);
try
{
    descContent = mytextbox.Text;
    var stringcontent = new StringContent(descContent);
    stringcontent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("description", descContent));
    multipart.Add(stringcontent);

    HttpResponseMessage res = await client.PostAsync(new Uri("http://localhost/web/test/index.php"), multipart);
    res.EnsureSuccessStatusCode();
    mytextbox.Text = await res.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
    mytextbox.Text = ex.Message;
}


this code will send the image file but not the description(string), i have searched over the internet but I could not find appropriate answer.
here is the PHP code

if (isset($_FILES['photo']))
{
    echo $_FILES["photo"]["name"] . "<br>";
}
else
{
    echo "Image: Error<br>";
}

if (isset($_POST['description']))
{
    echo $_POST['description'];
}   
else
{
    echo "Text: Error";
}


any response will be highly appreciated.
thank you

Upvotes: 2

Views: 1534

Answers (2)

Coding Bots
Coding Bots

Reputation: 41

I have search a lot and finally got the way out. here is the code

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://www.yourdomain.com");
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content  = new StringContent("your string type data you want to post");
form.Add(content, "name");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
    Name = "image",
    FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("index.php", form);
mytextblock.Text = response.Content.ReadAsStringAsync();

I wrote it on my blog here is the code. :-) HappyCoding

Upvotes: 1

Related Questions