This is one of the coolest features of HttpClient! See how easy it is to send files as part of the POST request:
First we create the HttpClient object and the POST method object. (lines 1-2)
Then we create a MutipartEntity. This type of entity enables us to send both string parameters and files in the same request. We then assign the MultipartEntity to be the PostMethod’s entity. (line 4-5)

Now we create a StringBody. We use StringBody to pass regular string parameters (very much the same as a regular POST request, only this is the way it done for a Multipart request). We add the StringBody to the MultipartEntity.(lines 7-8)

Here comes the interesting part: We create a FileBody object. This is used to send files as part of a MutipartPost request. We also need a FileInfo object to point to the file we want to send. The FileInfo needs the actual name and location of the file we want to send. The FileBody objects gets the pointer to the file as a parameter (fileInfo), and also we can decide what is the name of the file parameter, and what will be the file-name that will be passed to the server. We than add the FileBody to the MultipartEntity. (lines 10-12)

The rest of the code is pretty straight forward. We execute the request, and print the response status code, and content.


HttpClient client = new HttpClient();
HttpPost postMethod = new HttpPost(new Uri("http://www.w3schools.com/asp/demo_simpleform.asp"));

MultipartEntity multipartEntity = new MultipartEntity();
postMethod.Entity = multipartEntity;

StringBody stringBody = new StringBody(Encoding.UTF8, "firstName", "brian");
multipartEntity.AddBody(stringBody);

FileInfo fileInfo = new FileInfo(@"c:\temp\example.jpg");
FileBody fileBody = new FileBody("file1", "example.jpg", fileInfo);
multipartEntity.AddBody(fileBody);

HttpResponse response = client.Execute(postMethod);

Console.WriteLine("Response Code: " + response.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));

For this to work you will need the following using directives:

using System.IO;
using CodeScales.Http;
using CodeScales.Http.Methods;
using CodeScales.Http.Entity;
using CodeScales.Http.Entity.Mime;
using CodeScales.Http.Common;