0

PhotoChooser我有一个二进制流,它从windows phone 中的任务中获取照片流。我正在尝试将用户选择的图片上传到我的网络服务器上。

如何将照片流复制到 HttpRequest 流?

到目前为止,我有这样的东西

BinaryStream BStream = new BinaryStream(StreamFromPhotoChooser);
HttpRequest request = new HttpRequest()

我知道如何设置 HttpRequest 的属性,以便它上传到正确的位置。我唯一的问题是ACTUAL图片的上传。

4

1 回答 1

0

您可以通过获取请求流并将流写入其中来将二进制流写入或复制到请求流。这是一些您可能会发现对 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                
        }                   
}
于 2013-10-07T07:02:40.707 回答