Wednesday, May 7, 2014

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

No comments:

Post a Comment