让HttpWebRequest立即写入/上传,这样我就可以跟踪进度

时间:2013-10-28 17:27:36

标签: c# httpwebrequest progress webrequest

我一直在谷歌搜索这段时间没有运气。似乎还有许多人遇到过这个问题,但那些似乎没有解释他们如何解决这个问题的人。我试图应用其他人建议的所有东西(AllowWriteStreamBuffering,SendChunked),但仍然无法使其工作。

如果我运行以下代码,_data设置为30MB,则using(reqStream)块中的代码会在几分之一秒内执行,然后它会在request.GetResponse行停止,它似乎在上传。

我希望它在写入时上传块,以便我可以显示已上载的数据量,以显示进度。

我做错了什么?

static void Upload(string _url, Byte[] _data)
    {
        try
        {
            var request = WebRequest.Create(_url) as HttpWebRequest;
            request.Method = "PUT";
            request.ContentType = @"application/x-www-form-urlencoded";
            request.ContentLength = _data.Length;
            request.AllowWriteStreamBuffering = false;
            request.SendChunked = true;

            using (var reqStream = request.GetRequestStream())
            {
                var bytesWritten = 0;
                while (bytesWritten != _data.Length)
                {
                    var amountToWrite = Math.Min(1000000, _data.Length - bytesWritten);
                    reqStream.Write(_data, bytesWritten, amountToWrite);
                    reqStream.Flush();

                    // report progress

                    bytesWritten += amountToWrite;
                }
            }

            var response = request.GetResponse();
            var resStream = response.GetResponseStream();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

0 个答案:

没有答案