编程语言
首页 > 编程语言> > C#-通过HttpClient发送大文件

C#-通过HttpClient发送大文件

作者:互联网

我需要通过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与正确的标头一起使用很重要:

> Content-Disposition
> Content-Type

解决方法:

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

标签:console-application,c,net
来源: https://codeday.me/bug/20191110/2013552.html