上传文件用WebClient类和HttpWebRequest类都可以,但用WebClient无法获取服务器端的返回内容,至少我没发现有什么方法,哪位要是知道别忘了告诉下,谢谢
HttpWebRequest类代码:
1 /// <summary>
2 /// 发送内容
3 /// </summary>
4 private byte[] bSendingFile = null;
5
6
7
8 using (IsolatedStorageFileStream sendingZipStream2 = new IsolatedStorageFileStream(strZipFolderName + "/" + strZipFileName, FileMode.Open, isoStorage))
9 {
10 try
11 {
12 // 要上传的文件
13 bSendingFile = new byte[sendingZipStream2.Length];
14 sendingZipStream2.Read(bSendingFile, 0, bSendingFile.Length);
15
16 // 根据uri创建HttpWebRequest对象
17 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(F3StaticResource.SendNMSUrl, UriKind.Absolute));
18 httpReq.Method = "POST";
19 httpReq.ContentType = "multipart/form-data;";
20
21 IAsyncResult asyncResult = httpReq.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), httpReq);
22 }
23 catch(Exception ex)
24 {
25 String strError = ex.ToString();
26 }
27
28 }
29
30
31
32 /// <summary>
33 /// 返回用于将数据写入Stream,写入数据,并发送
34 /// </summary>
35 /// <param name="result"></param>
36 private void RequestStreamCallback(IAsyncResult result)
37 {
38 HttpWebRequest request = result.AsyncState as HttpWebRequest;
39
40 // 返回用于将数据写入某 URI 资源的 Stream
41 Stream requestStream = request.EndGetRequestStream(result);
42
43 requestStream.Write(bSendingFile, 0, bSendingFile.Length);
44 requestStream.Flush();
45 requestStream.Close();
46
47 request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
48 }
49
50 /// <summary>
51 /// 获取最终的返回结果
52 /// </summary>
53 /// <param name="result"></param>
54 private void ResponseCallback(IAsyncResult result)
55 {
56 try
57 {
58 HttpWebRequest request = result.AsyncState as HttpWebRequest;
59 WebResponse response = request.EndGetResponse(result) as HttpWebResponse;
60
61 if (response != null)
62 {
63 Stream responseStream = response.GetResponseStream();
64 using (StreamReader streamReader = new StreamReader(responseStream))
65 {
66 String strResponese = streamReader.ReadToEnd();//返回内容
67
68 }
69
70 }
71 }
72 catch (Exception ex)
73 {
74 String strError = ex.ToString();
75 }
76 }