1

我一直在尝试将图像发送到宁静的服务和一些数据。但是我可以发送数据(图像的名称和描述),并且我创建了 sql 数据库来存储数据并在其上添加了数据,但我无法将图像发送到服务器。

服务代码:

    [WebInvoke(UriTemplate = "UploadPhoto/{fileName}/{description}", Method = "POST")]
    public void UploadPhoto(string fileName, string description, Stream fileContents)
    {
        byte[] buffer = new byte[32768];
        MemoryStream ms = new MemoryStream();
        int bytesRead, totalBytesRead = 0;
        do
        {
            bytesRead = fileContents.Read(buffer, 0, buffer.Length);
            totalBytesRead += bytesRead;

            ms.Write(buffer, 0, bytesRead);
        } while (bytesRead > 0);

        // Save the photo on database.
        using (DataAcess data = new DataAcess())
        {
            var photo = new Photo() { Name = fileName, Description = description, Data = ms.ToArray(), DateTime = DateTime.UtcNow,  };
            data.InsertPhoto(photo);
        }

        ms.Close();
        Console.WriteLine("Uploaded file {0} with {1} bytes", fileName, totalBytesRead);
    }

这是我在客户端的代码。我在windows phone 7上做。

 void btnNewPhoto_Click(object sender, RoutedEventArgs e)
    {
        Uri uri = new Uri("http://localhost:2557/photos");
        string requestUrl = string.Format("{0}/UploadPhoto/{1}/{2}", uri, System.IO.Path.GetFileName(txtFileName.Text), txtDescription.Text);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
        request.Method = "POST";
        request.BeginGetRequestStream
            (result =>
            {
                // Sending the request.
                using (var requestStream = request.EndGetRequestStream(result))
                {
                    using (StreamWriter writer = new StreamWriter(requestStream))
                    {
                        BinaryReader reader = new BinaryReader(requestStream);
                        string s = imgPhoto.ToString();
                        byte[] byteArray = Encoding.UTF8.GetBytes(s.ToString());
                        requestStream.Write(byteArray, 0, byteArray.Length);

                        requestStream.Close();
                        requestStream.Dispose();
                        //writer.Write(requestUrl);
                        //writer.Flush();

                    }
                }



                // Getting the response.
                request.BeginGetResponse(responseResult =>
                {
                    var webResponse = request.EndGetResponse(responseResult);
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        using (var streamReader = new StreamReader(responseStream))
                        {

                            string srresult = streamReader.ReadToEnd();
                        }
                    }
                }, null);
            }, null);
    }
4

0 回答 0