Showing posts with label HttpClient. Show all posts
Showing posts with label HttpClient. Show all posts

Monday, May 12, 2014

Wednesday, May 7, 2014

Calling Web API from a Windows Phone 8 Application

Robert McMurray has posted a great tutorial on the ASP.Net site from Microsoft.
It combines some APIs want to get a better handle on Web API, HttpClient and
the Windows Phone API


http://www.asp.net/web-api/overview/web-api-clients/calling-web-api-from-a-windows-phone-8-application

How to do a multipart post with file upload using WebApi HttpClient

Problem:  My app needs to submit a user form to a web backend.  There are a number
of easy ways to do this via the WP8 SDK to upload files.  These are all done pretty much
with GETs vice POSTS.  I looked around for some solutions to do a multipart submittal since
my form will have files as well as text to submit. The only issue is getting the files as byte arrays.
I will do a post on this particular issue at another time.



Solution:

Form:

     <form action="/api/workitems" enctype="multipart/form-data" method="post">
        <input type="hidden" name="type" value="ExtractText" />
        <input type="file" name="FileForUpload" />
        <input type="submit" value="Run test" />
    </form>


Code behind
 using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        var values = new[]
        {
            new KeyValuePair<string, string>("Foo", "Bar"),
            new KeyValuePair<string, string>("More", "Less"),
        };
        foreach (var keyValuePair in values)
        {
            content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
        }
        var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Foo.txt"
        };
        content.Add(fileContent);
        var requestUri = "/api/action";
        var result = client.PostAsync(requestUri, content).Result;
    }
}

Source:
http://stackoverflow.com/questions/10339877/asp-net-webapi-how-to-perform-a-multipart-post-with-file-upload-using-webapi-ht