Silverlight Http Post上传图片

时间:2010-10-01 08:02:11

标签: c# silverlight file-upload httpwebrequest windows-phone-7

我一直在尝试执行HTTP Post请求,以便在用于Windows Phone 7应用程序的silverlight应用程序中上传图像。在线示例代码没有从API获得所需的响应。有人可以提供一个可以做到这一点的工作代码吗?

通过所需的响应,我的意思是API回应说上传的文件是无法读取的格式。

提前致谢!

这是我的代码:

 private void post_image(version, username,password,job-id, serviceUri)
    {
        if (session_free.bLoggedIn)
        {                
            bool submit_success = false;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(serviceUri));

            IsolatedStorageFileStream stream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("file.jpg", FileMode.Open);

            request.PostMultiPartAsync(new Dictionary<string, object> { { "version", version }, { "username", user }, { "password", pass }, { filename, stream } }, new AsyncCallback(asyncResult =>
            {

                Thread.Sleep(1000);

                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                Post_Result = reader.ReadToEnd();

                this.Dispatcher.BeginInvoke(delegate
                {
                   MessageBox.Show(Post_Result);
                    response.Close();
                });
            }), filename);

            Thread.Sleep(1000);
        }

        else
        {
            MessageBox.Show("User not signed in! Please login to continue...", "Invalid Authentication", MessageBoxButton.OK);
        }
    }

    public class DataContractMultiPartSerializer
{
    private string boundary;

    public DataContractMultiPartSerializer(string boundary)
    {
        this.boundary = boundary;
    }

    private void WriteEntry(StreamWriter writer, string key, object value, string filename)
    {

        if (value != null)
        {
            writer.Write("--");
            writer.WriteLine(boundary);
            if (value is IsolatedStorageFileStream)
            {
                IsolatedStorageFileStream f = value as IsolatedStorageFileStream;
                writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, filename);
                writer.WriteLine("Content-Type: image/jpeg");
                writer.WriteLine("Content-Length: " + f.Length);
                writer.WriteLine();
                writer.Flush();
                Stream output = writer.BaseStream;
                Stream input = f;
                byte[] buffer = new byte[4096];
                for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                {
                    output.Write(buffer, 0, size);
                }
                output.Flush();
                writer.WriteLine();
            }

            else
            {
                writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""", key);
                writer.WriteLine();
                writer.WriteLine(value.ToString());
            }
        }
    }

    public void WriteObject(Stream stream, object data, string filename)
    {
        StreamWriter writer = new StreamWriter(stream);
        if (data != null)
        {


            if (data is Dictionary<string, object>)
            {
                foreach (var entry in data as Dictionary<string, object>)
                {
                    WriteEntry(writer, entry.Key, entry.Value, filename);
                }
            }

            else
            {
                foreach (var prop in data.GetType().GetFields())
                {
                    foreach (var attribute in prop.GetCustomAttributes(true))
                    {
                        if (attribute is System.Runtime.Serialization.DataMemberAttribute)
                        {
                            DataMemberAttribute member = attribute as DataMemberAttribute;
                            writer.Write("{0}={1}&", member.Name ?? prop.Name, prop.GetValue(data));
                        }
                    }
                }
            }
            writer.Flush();
        }
    }
}

1 个答案:

答案 0 :(得分:6)

您是否有使用多部分信息的原因? 您使用的PostMultiPartAsync方法是什么?据推测,这是从某个地方扩展的方法? 将来,请尝试提供最小,最完整的代码,以证明问题。

无论如何,对不起,这不是一个完整的工作示例,但以下是实现此目的的一种方法的步骤。

创建请求并为BeginGetRequestStream

设置回溯
var request = (HttpWebRequest)WebRequest.Create(App.Config.ServerUris.Login);

request.Method = "POST";
request.BeginGetRequestStream(ReadCallback, request);

在该回调中,获取请求流并将数据写入其中。

using (var postStream = request.EndGetRequestStream(asynchronousResult))
{
    // Serialize image to byte array, or similar (that's what imageBuffer is)
    postStream.Write(imageBuffer, 0, imageBuffer.Length);
}

为服务器的响应设置回调。

request.BeginGetResponse(ResponseCallback, request);

检查服务器上的所有内容是否正常

private void ResponseCallback(IAsyncResult asynchronousResult)
{
    var request = (HttpWebRequest)asynchronousResult.AsyncState;

    using (var resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
    {
        using (var streamResponse = resp.GetResponseStream())
        {
            using (var streamRead = new StreamReader(streamResponse))
            {
                string responseString = streamRead.ReadToEnd();  // Assuming that the server will send a text based indication of upload success

                // act on the response as appropriate
            }
        }
    }
}

在服务器上,您需要反序列化数据并将其转换回适当的图像。

HTH。