上传文件用WebClient类和HttpWebRequest类都可以,但用WebClient无法获取服务器端的返回内容,至少我没发现有什么方法 HttpWebRequest类代码:
- /// <summary>
- /// 发送内容
- /// </summary>
- private byte[] bSendingFile = null;
-
-
-
- using (IsolatedStorageFileStream sendingZipStream2 = new IsolatedStorageFileStream(strZipFolderName + "/" + strZipFileName, FileMode.Open, isoStorage))
- {
- try
- {
- // 要上传的文件
- bSendingFile = new byte[sendingZipStream2.Length];
- sendingZipStream2.Read(bSendingFile, 0, bSendingFile.Length);
-
- // 根据uri创建HttpWebRequest对象
- HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(F3StaticResource.SendNMSUrl, UriKind.Absolute));
- httpReq.Method = "POST";
- httpReq.ContentType = "multipart/form-data;";
-
- IAsyncResult asyncResult = httpReq.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), httpReq);
- }
- catch(Exception ex)
- {
- String strError = ex.ToString();
- }
-
- }
-
-
-
- /// <summary>
- /// 返回用于将数据写入Stream,写入数据,并发送
- /// </summary>
- /// <param name="result"></param>
- private void RequestStreamCallback(IAsyncResult result)
- {
- HttpWebRequest request = result.AsyncState as HttpWebRequest;
-
- // 返回用于将数据写入某 URI 资源的 Stream
- Stream requestStream = request.EndGetRequestStream(result);
- //此处直接写到stream中会有错误,要对流进行组装
- requestStream.Write(bSendingFile, 0, bSendingFile.Length);
- requestStream.Flush();
- requestStream.Close();
-
- request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
- }
-
- /// <summary>
- /// 获取最终的返回结果
- /// </summary>
- /// <param name="result"></param>
- private void ResponseCallback(IAsyncResult result)
- {
- try
- {
- HttpWebRequest request = result.AsyncState as HttpWebRequest;
- WebResponse response = request.EndGetResponse(result) as HttpWebResponse;
-
- if (response != null)
- {
- Stream responseStream = response.GetResponseStream();
- using (StreamReader streamReader = new StreamReader(responseStream))
- {
- String strResponese = streamReader.ReadToEnd();//返回内容
-
- }
-
- }
- }
- catch (Exception ex)
- {
- String strError = ex.ToString();
- }
- }
多上传的stream进行组装
// 返回用于将数据写入某 URI 资源的 Stream
Stream requestStream = request.EndGetRequestStream(result);
// 构造发送数据
StringBuilder sb = new StringBuilder();
// 文件域的数据
sb.Append("--" + boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"upload_file\";filename=\"image.wav\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("audio/wav");
sb.Append("\r\n\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
requestStream.Write(bSendingFile, 0, bSendingFile.Length);
byte[] b3 = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");
requestStream.Write(b3, 0, b3.Length);
requestStream.Flush();
requestStream.Close();