我正在开发一个Silverlight自定义控件,我使用WebClient将一些XML数据发送到我的服务器。上传文件后,我需要运行一个回调函数。那么,问题是如何知道上传文件? 这是我写的代码:
WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
Uri uri = new Uri(myUrl);
wc.OpenWriteAsync(uri, "POST", data);
...
private void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e){
if (e.Error == null)
{
byte[] fileContent = e.UserState as byte[];
Stream outputStream = e.Result;
outputStream.Write(fileContent, 0, fileContent.Length);
outputStream.Flush();
outputStream.Close();
}
HtmlPage.Window.Invoke("callBackFunction");
}
这一切对我来说都很好,但有两个问题。我不确定文件上传完成后wc_OpenWriteCompleted是否实际运行。我该如何确认?回调函数,如果文件不完整,它将不会做任何事情。这是回电话的正确位置吗?最后,服务器在调用后响应一些测试,如何将其传递给我的回调函数?
答案 0 :(得分:0)
您可以尝试创建服务请求。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(SessionConstants.serviceURL, UriKind.Absolute));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(ObjectListRequestReady), request);
然后将服务请求发送到服务器以上传文件。
void ObjectListRequestReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
Stream stream = request.EndGetRequestStream(asyncResult);
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
SELECTED_NODE = SPSITETextBox.Text;
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine("pass your data to upload on server");
writer.Flush();
writer.Close();
request.BeginGetResponse(new AsyncCallback(ObjectListResponseReady), request);
// ObjectListResponseReady is the callback method called after uploading the data.
});
}
从服务中获取结果。 ObjectListResponseReady
是一种回调方法,可以在上传文件后回复您。
void ObjectListResponseReady(IAsyncResult asyncResult)
{
try
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
Stream responseStream = response.GetResponseStream();
XmlReader xmlReader = XmlReader.Create(responseStream);
});
}
catch (Exception ex)
{
Message.ErrorMessage("error: " + ex);
}
}