开发者

Asynchronous upload using HttpWebRequest

I have a dot net windows application which uploads large files to an intranet website. While the开发者_运维知识库 upload is working fine, I would also like to know the progress of the upload.

I see that webRequest.GetResponse() is the line that is taking time. The control just came out from GetRequestStream almost immediately and I assume that this happens locally and does not require a server connection.

using (var reqStream = webRequest.GetRequestStream())
{
    reqStream.Write(tempBuffer, 0, tempBuffer.Length);
}

I tried converting it to an Async call, but it is also taking the same time to reach the RespCallback method.

IAsyncResult result = (IAsyncResult)webRequest.BeginGetResponse(new AsyncCallback(RespCallback), requestState);

private void RespCallback(IAsyncResult asyncResult)
{
    WebRequestState reqState = ((WebRequestState)(asyncResult.AsyncState));
}

I would like tracking the bytes that are sent to the server so as to show a progress bar. How can I do that?


Did you tried WebClient class? And UploadXXXAsyn() methods?


Think of hte Asyncronous upload as a separate thread, once it has uploaded the information, the rest of the program runs and the event handler fires once a response is recieved.

You should be using the WebClient class.

So for example:

public string result; //Variable for returned data to go.

public void UploadInfo(string URL, string data)
{

WebClient client = new WebClient(); //Create new instance of WebClient

client.UploadStringCompeleted += new UploadStringCompletedEventHandler(client_uploadComplete); //Tell client what to do once upload complete

client.UploadStringAsync(new uri(URL), data); //Send data to URL specified

}


public void client_uploadComplete(object sender, UploadStringCompletedEventArgs e)
{

if (e.Error == null) //If server does not return error
{
result = e.Result; //Place returned value into "result" string
}

}

Thats just a basic bit of code, i am unsure if it will work for you as it will depend on what server side tech you are using plus other factors, but it should point you in the right direction.

If you are using some find of server side data-interchange format, for example json, you will need the following line before you send info to the server.

client.Headers[HttpRequestHeader.ContentType] = "application/json"; 

make sure you change "application/json" to whatever you are using.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜