5

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?

Shawn
  • 2,356
  • 6
  • 48
  • 82

2 Answers2

6

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);
Rob G
  • 3,496
  • 1
  • 20
  • 29
  • I did end up doing this, but because I ended up saving the file to disk and then reading it in as such. Can you only append files that are currently saved to the disk? I was trying to avoid doing so which is why I was attaching a stream. – Shawn Oct 02 '13 at 16:18
  • So in the result no need for Stream fileStream in method parameters, right? – Prokurors Aug 26 '16 at 09:28
  • @rob-g can I find one complete working example of your suggested impliemtation ? – vibs2006 Mar 13 '18 at 06:10
0

Turns out the fileStream wasn't getting to the method. Using context.Request.Files[0].InputStream seemed to be the culprite. Using .SaveAs and then reading it in as a byteArray and attaching that to the MultiPartFormDataContent worked.

Shawn
  • 2,356
  • 6
  • 48
  • 82