使用 Microsoft.Net.Http 将文件发送到服务

Sha*_*awn 5 c# upload file-upload multipartform-data httpcontent

我有一个方法:

    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;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

即将文件发送到 WCF 服务,但查看帖子的 Wireshark 日志,不会附加 fileStream,仅附加文件名。我还需要做其他事情吗?

Rob*_*b G 6

使用 aByteArrayContent而不是流内容。

 var fileContent = new ByteArrayContent(File.ReadAllBytes(fileName));
Run Code Online (Sandbox Code Playgroud)

然后指定您的内容处置标头:

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

formData.Add(fileContent);
Run Code Online (Sandbox Code Playgroud)