Send file to service using Microsoft.Net.Http

Shawn picture Shawn · Oct 2, 2013 · Viewed 8.8k times · Source

I have a method:

    private bool UploadFile(Stream fileStream, string fileName)
    {
            HttpContent fileStreamContent = new StreamContent(fileStream);
            using (var client = new HttpClient())
            {
                using (var formData = new MultipartFormDataContent())
                {
                    formData.Add(fileStreamContent, fileName, fileName);

                    var response = client.PostAsync("url", formData).Result;

                    return response.StatusCode == HttpStatusCode.OK;
                }
            }
        }
    }

That is sending the file to a WCF service, but looking at the Wireshark log of the post, the fileStream isn't being appended, just the filename. Do I need to do something else?

Answer

Rob G picture Rob G · Oct 2, 2013

Use a ByteArrayContent instead of a stream content.

 var fileContent = new ByteArrayContent(File.ReadAllBytes(fileName));

Then specify your content disposition header:

fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = fileName
};

formData.Add(fileContent);