您可以通过获取请求流并将流写入其中来将二进制流写入或复制到请求流。这是一些您可能会发现对 HttpWebRequest 的 Web 请求有用的代码,并且您在 httpRequest Stream 中处理照片流的问题在 GetRequestStreamCallback() 中完成
private void UploadClick()
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("your URL of server");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
//your binary stream to upload
BinaryStream BStream = new BinaryStream(StreamFromPhotoChooser);
//copy your data to request stream
BStream.CopyTo(postStream);
//OR
byte[] byteArray = //get bytes of choosen picture
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
//Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (WebException e)
{
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
//to read server responce
Stream streamResponse = response.GetResponseStream();
string responseString = new StreamReader(streamResponse).ReadToEnd();
// Close the stream object
streamResponse.Close();
// Release the HttpWebResponse
response.Close();
Dispatcher.BeginInvoke(() =>
{
//Update UI here
});
}
}
catch (WebException e)
{
//Handle non success exception here
}
}