我必须使用以下代码段将大文件上传到服务器:
static async Task LordNoBugAsync(string token, string filePath, string uri)
{
HttpWebRequest fileWebRequest = (HttpWebRequest)WebRequest.Create(uri);
fileWebRequest.Method = "PATCH";
fileWebRequest.AllowWriteStreamBuffering = false; //this line tells to upload by chunks
fileWebRequest.ContentType = "application/x-www-form-urlencoded";
fileWebRequest.Headers["Authorization"] = "PHOENIX-TOKEN " + token;
fileWebRequest.KeepAlive = false;
fileWebRequest.Timeout = System.Threading.Timeout.Infinite;
fileWebRequest.Proxy = null;
using (FileStream fileStream = File.OpenRead(filePath) )
{
fileWebRequest.ContentLength = fileStream.Length; //have to provide length in order to upload by chunks
int bufferSize = 512000;
byte[] buffer = new byte[bufferSize];
int lastBytesRead = 0;
int byteCount = 0;
Stream requestStream = fileWebRequest.GetRequestStream();
requestStream.WriteTimeout = System.Threading.Timeout.Infinite;
while ((lastBytesRead = fileStream.Read(buffer, 0, bufferSize)) != 0)
{
if (lastBytesRead > 0)
{
await requestStream.WriteAsync(buffer, 0, lastBytesRead);
//for some reasons didnt really write to stream, but in fact buffer has content, >60MB
byteCount += bufferSize;
}
}
requestStream.Flush();
try
{
requestStream.Close();
requestStream.Dispose();
}
catch
{
Console.Write("Error");
}
try
{
fileStream.Close();
fileStream.Dispose();
}
catch
{
Console.Write("Error");
}
}
...getting response parts...
}
在代码中,我创建了一个HttpWebRequest,并通过缓冲将内容推送到服务器。该代码适用于60MB以下的任何文件。
我尝试了70MB的pdf。缓冲区阵列对于每个缓冲具有不同的内容。然而,请求流似乎没有被写入。 bytecount也达到70M,显示文件已正确读取。
编辑(更多信息):我在requestStream.Close()处设置了断点。请求流显然需要大约2分钟才能写入60MB文件,但70MB文件只需要2ms。
我的呼唤:
Task magic = LordNoBugAsync(token, nameofFile, path);
magic.Wait();
我确信我的通话是正确的(适用于0B到60MB的文件)。
非常感谢任何建议或建议。