使用HttpWebRequest异步上传 [英] Asynchronous upload using HttpWebRequest

查看:268
本文介绍了使用HttpWebRequest异步上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个点网Windows应用程序,该应用程序将大文件上传到Intranet网站.在上传正常进行的同时,我还想知道上传的进度.

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.

我看到webRequest.GetResponse()是花费时间的一行.该控件几乎是从GetRequestStream出来的,我认为这是在本地发生的,不需要服务器连接.

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);
}

我尝试将其转换为Async调用,但也需要花费相同的时间才能到达RespCallback方法.

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?

推荐答案

将hte异步上传作为单独的线程考虑,一旦它上传了信息,程序的其余部分就会运行,并且一旦收到响应,事件处理程序就会触发

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.

您应该使用 WebClient 类.

例如:

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.

如果使用某种服务器端数据交换格式(例如json),则在将信息发送到服务器之前,需要以下行.

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"; 

确保将"application/json"更改为正在使用的内容.

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

祝你好运!

这篇关于使用HttpWebRequest异步上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆