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

我有一个方法:

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

即将文件发送到WCF服务,但查看帖子的Wireshark日志,不会追加fileStream,只是文件名.我还需要做点什么吗?

最佳答案 使用ByteArrayContent而不是流内容.

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

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

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

formData.Add(fileContent);
点赞