我将一些表单数据(包括文件)上传到Web服务器,并需要跟踪上传进度。我是通过将我的上传数据逐位复制到HttpWebRequest
的请求流并根据复制的字节数和总字节数更新进度条来实现的。根据另一个网站,这将缓冲一切,之后实际的网络传输需要更长的时间。我应该设置request.AllowWriteStreamBuffering = false;
以防止缓冲。不幸的是,当我这样做时,request.GetResponse()
方法会永远阻止。
以下是一些示例代码:
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uri);
request.AllowAutoRedirect = false;
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + multipartBoundary;
Stream reqStream = request.GetRequestStream();
request.AllowWriteStreamBuffering = false;
postStream.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) > 0)
{
reqStream.Write(buffer, 0, bytesRead);
int percentage = (int) (postStream.Position * 100 / postStream.Length);
backgroundWorker.ReportProgress(percentage);
}
reqStream.Close();
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
当我没有设置AllowWriteStreamBuffering
时,一切正常。这里有什么问题?
答案 0 :(得分:0)
问题是设置AllowWriteStreamBuffering
为时已晚。这很好用:
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uri);
request.AllowWriteStreamBuffering = false;
request.SendChunked = true;
request.AllowAutoRedirect = false;
request.Method = "POST";
...
通过提前设置AllowWriteStreamBuffering
,它还告诉我一个例外情况,即我必须设置SendChunked
或指定内容长度(我现在手头没有)。