Send a file via HTTP POST with C#
Using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) there is an easier way to simulate form requests. Here is an example:
private async Task<System.IO.Stream> Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
HttpContent stringContent = new StringContent(paramString);
HttpContent fileStreamContent = new StreamContent(paramFileStream);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "param1", "param1");
formData.Add(fileStreamContent, "file1", "file1");
formData.Add(bytesContent, "file2", "file2");
var response = await client.PostAsync(actionUrl, formData);
if (!response.IsSuccessStatusCode)
{
return null;
}
return await response.Content.ReadAsStreamAsync();
}
}
To send the raw file only:
using(WebClient client = new WebClient()) {
client.UploadFile(address, filePath);
}
If you want to emulate a browser form with an <input type="file"/>
, then that is harder. See this answer for a multipart/form-data answer.
For me client.UploadFile
still wrapped the content in a multipart request so I had to do it like this:
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type", "application/octet-stream");
using (Stream fileStream = File.OpenRead(filePath))
using (Stream requestStream = client.OpenWrite(new Uri(fileUploadUrl), "POST"))
{
fileStream.CopyTo(requestStream);
}
}