通过 HttpClient 发送大文件

Jak*_*mpl 4 .net c# console-application

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

多亏了这篇文章,我才能用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)
}
Run Code Online (Sandbox Code Playgroud)

但是,我想通过HttpClient. 我找到了描述使用 of 的文章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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

也许我忽略了或错过了一些东西......


更新

最重要的是,使用StreamContent正确的标题很重要:

Cor*_*son 5

StreamContent班级:

HttpResponseMessage response =
    await httpClient.PostAsync("http://....", new StreamContent(streamToSend));
Run Code Online (Sandbox Code Playgroud)

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

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