使用HttpWebRequest监控上载进度

时间:2016-02-09 18:07:24

标签: c# xamarin httpwebrequest multipartform-data

我最近编写了一个C#函数,用于上传文件的多部分表单。为了跟踪进度,我将表单数据一次以4096字节写入请求流,并在每次写入时回调。但是,在调用GetResponseAsync()之前,似乎甚至没有发送请求。

如果是这种情况,那么写入请求流的每4096个字节的报告是否准确报告了上传进度?

如果没有,我该如何准确报告进度? WebClient对我来说是不可能的,这是在PCL Xamarin项目中。

    private async Task<string> PostFormAsync (string postUrl, string contentType, byte[] formData)
    {
        try {
            HttpWebRequest request = WebRequest.Create (postUrl) as HttpWebRequest;

            request.Method = "POST";
            request.ContentType = contentType;

            request.Headers ["Cookie"] = Constants.Cookie;

            byte[] buffer = new byte[4096];
            int count = 0;
            int length = 0;
            using (Stream requestStream = await request.GetRequestStreamAsync ()) {
                using (Stream inputStream = new MemoryStream (formData)) {

                    while ((count = await inputStream.ReadAsync (buffer, 0, buffer.Length)) > 0) {
                        await requestStream.WriteAsync (buffer, 0, count);
                        length += count;
                        Device.BeginInvokeOnMainThread (() => {
                            _progressBar.Progress = length / formData.Length;
                        });
                    }   
                }
            }
            _progressBar.Progress = 0;

            WebResponse resp = await request.GetResponseAsync ();

            using (Stream stream = resp.GetResponseStream ()) {
                StreamReader respReader = new StreamReader (stream);
                return respReader.ReadToEnd ();
            }

        } catch (Exception e) {

            Debug.WriteLine (e.ToString ());
            return String.Empty;
        }
    }

请注意,我要求一次监控上传的进度为4096字节,而不是下载

1 个答案:

答案 0 :(得分:3)

我最终通过将WebRequest的AllowWriteStreamBuffering属性设置为false并将SendChunked属性设置为true来完成此操作。

然而,Xamarin.PCL(Profile 78)不允许您访问HttpWebRequest的这些属性,因此我必须实例化我的HttpWebRequest并从我的平台特定项目中的依赖服务返回它(仅在iOS中测试)。 / p>

public class WebDependency : IWebDependency
{
    public HttpWebRequest GetWebRequest(string uri)
    {
        var request = WebRequest.Create (uri) as HttpWebRequest;
        request.SendChunked = true;
        request.AllowWriteStreamBuffering = false;

        return request;

    }

}

然后实例化我的网络请求 -

HttpWebRequest request = DependencyService.Get<IWebDependency>().GetWebRequest(uri);