I need to upload large files (~200MB) over HTTP protocol. I want to avoid loading the files to memory and want to send them directly.
Thanks to this article I was able to make it with 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)
}
However, I would like to do it via HttpClient
. I found article which describes using of HttpCompletionOption.ResponseHeadersRead
and I tried something like this but it does not work unfortunately.
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
}
}
}
Maybe I overlooked or missed something...
UPDATE
On top of it, it is important to use StreamContent
with proper headers: