通过HttpClient发送大文件

时间:2018-01-19 15:50:48

标签: c# .net console-application

我需要通过HTTP协议上传大文件(~200MB)。我想避免将文件加载到内存并希望直接发送它们。

感谢article我能够使用HttpWebRequest

HttpWebRequest requestToServer = (HttpWebRequest)WebRequest.Create("....");

requestToServer.AllowWriteStreamBuffering = false;
requestToServer.Method = WebRequestMethods.Http.Post;
requestToServer.ContentType = "multipart/form-data; boundary=" + boundaryString;
requestToServer.KeepAlive = false;
requestToServer.ContentLength = ......;

using (Stream stream = requestToServer.GetRequestStream())
{
    // write boundary string, Content-Disposition etc.
    // copy file to stream
    using (var fileStream = new FileStream("...", FileMode.Open, FileAccess.Read))
    {
        fileStream.CopyTo(stream);
    }

    // add some other file(s)
}

但是,我想通过HttpClient来完成。我发现article描述了HttpCompletionOption.ResponseHeadersRead的使用情况,我试过这样的事情,但遗憾的是它不起作用。

WebRequestHandler handler = new WebRequestHandler();

using (var httpClient = new HttpClient(handler))
{
    httpClient.DefaultRequestHeaders.Add("ContentType", "multipart/form-data; boundary=" + boundaryString);
    httpClient.DefaultRequestHeaders.Add("Connection", "close");

    var httpRequest = new HttpRequestMessage(HttpMethod.Post, "....");

    using (HttpResponseMessage responseMessage = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead))
    {
        using (Stream stream = await responseMessage.Content.ReadAsStreamAsync())
        {
            // here I wanted to write content to the stream, but the stream is available only for reading
        }
    }
}

也许我忽视或遗漏了某些事情......

更新

除此之外,使用StreamContent和正确的标题非常重要:

1 个答案:

答案 0 :(得分:3)

请参阅StreamContent课程:

HttpResponseMessage response =
    await httpClient.PostAsync("http://....", new StreamContent(streamToSend));

在您的示例中,您正在获取响应流并尝试写入它。相反,您必须传递请求的内容,如上所述。

HttpCompletionOption.ResponseHeadersRead是禁用缓冲响应流,但不影响请求。如果您的回复很大,通常会使用它。

要发布多个表单数据文件,请使用MultipartFormDataContent

var content = new MultipartFormDataContent();

content.Add(new StreamContent(stream1), "file1.jpg");
content.Add(new StreamContent(stream2), "file2.jpg");

HttpResponseMessage response =
    await httpClient.PostAsync("http://...", content);