Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top