HttpWebRequest& UploadProgressChanged?

时间:2010-08-08 00:15:25

标签: c# httpwebrequest

如何使用HttpWebRequest.BeginGetResponse获取进度更改事件以上传POST方法?

我现在的守则的一部分是:

HttpWebRequest req = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(uploadUri);

req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary + "";

req.ContentLength = dataBuffer.Length;

req.AllowReadStreamBuffering = false;
req.AllowWriteStreamBuffering = false;

DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
    ProgressText = "Waiting for request stream...";
});

req.BeginGetRequestStream(new AsyncCallback(GotRequestStreamForUpload), new SendPhotoAsyncState(req, dataBuffer, photo));

对BeginGetResponse的调用:

request.BeginGetResponse(new AsyncCallback(GotResponseStreamForUpload), new SendPhotoAsyncState(request, null, flickRPhoto));

如何告知我希望收到有关流中更改的通知?

我希望能够根据照片上传的进度更新用户界面...

以下代码不适用于WebClient:

       WebClient wc = new WebClient();

        wc.UploadStringCompleted += (s, e) =>
            {
                // What photo is this ?
                FlickRUploadPhoto fup = ((SendPhotoAsyncState)e.UserState).FlickrPhoto2Upload;
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    fup.tCompleted = DateTime.Now;
                    FileUploadComplete(this, new FlickRUploadCompleteEventArgs(fup));
                });

            };

        wc.UploadProgressChanged += (s2,e2) =>
            {

                // Was there an error ?

                // What photo is this ?
                FlickRUploadPhoto fup = ((SendPhotoAsyncState)e2.UserState).FlickrPhoto2Upload;
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        fup.ProgressPercentage = e2.ProgressPercentage;
                        fup.ProgressPercentageString = e2.ProgressPercentage.ToString() + "%";
                        fup.BytesUploaded = e2.BytesSent;
                    });
            };


        string data = dataBuffer.ToString();
        wc.UploadStringAsync(uploadUri, "POST", data , new SendPhotoAsyncState(null, dataBuffer, photo));

这是Silverlight ......所以我必须使用UploadStringAsync ??

1 个答案:

答案 0 :(得分:2)

您无法使用HttpWebRequest执行此操作,但您可以使用WebClient执行此操作:

    public void Upload(string targetUri, string filePath)
    {
        WebClient client = new WebClient();
        client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
        client.UploadFile(targetUri, filePath);
    }

如果您没有本地文件,请使用UploadData:

public void Upload(string targetUri, byte[] buffer)
    {
        WebClient client = new WebClient();
        client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
        client.UploadData(targetUri, buffer);
    }