gpt4 book ai didi

c# - 通过 HttpClient 发送大文件

转载 作者:行者123 更新时间:2023-12-02 01:31:47 25 4
gpt4 key购买 nike

我需要通过 HTTP 协议(protocol)上传大文件 (~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
}
}
}

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

<小时/>

更新

最重要的是,使用带有适当 header 的 StreamContent 非常重要:

最佳答案

请参阅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);

关于c# - 通过 HttpClient 发送大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48344819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com