简体   繁体   中英

Send file to service using Microsoft.Net.Http

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM