michielpost.nl

Uploading a file with Windows 8 WinRT

16-07-2012

There are multiple ways of uploading a file over Http in Windows 8 WinRT / Metro apps.

There's a great HttpClient sample provided in the Official Windows SDK Sample Pack:
http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664

Sample 5 shows a basic scenario where you only want to upload file data. But what if you want to mix file data and form/text values?

Scenario 6 is really powerful. It uses the MultipartFormDataContent class to create a request like a form's POST request.
MultipartFormDataContent form = new MultipartFormDataContent();

You can add multiple types of content to this "form". For example a simple string:
form.Add(new StringContent("mystring"), "formkey");

If we want to simulate a POST request that submits a form with both text values and a file, we can also add file data (as byte array):
var fileContent = new System.Net.Http.ByteArrayContent(bytes);
form.Add(fileContent, "file");

Optionally you can add extra headers:
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
fileContent.Headers.ContentDisposition.FileName = "filename";

Comments


No comments yet.

New Comment

Name
E-mail (not published)
Comment
Enter the code shown: