Silverlight Http Post 上传图片

发布于 2024-09-26 00:34:27 字数 4217 浏览 2 评论 0原文

我一直在尝试执行 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();
        }
    }
}

I have been trying to perform an HTTP Post request to upload an image in a silverlight application for a windows phone 7 application. The sample codes online do not get me the desired response from the API. Could anyone please provide a working code which does this?

By desired response I mean that the API responds saying that the uploaded file is in a format which cannot be read.

Thanks in advance!

Here is my code:

 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();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罪歌 2024-10-03 00:34:27

您使用多部分消息有什么原因吗?
您使用的 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。

Is there a reason you're using a multipart message?
What is the PostMultiPartAsync method you're using? Presumably it's an extension method from somewhere?
In future, try and provide the smallest, complete, piece of code which demonstrates the issue.

Anyway, sorry it's not a full working example, but here are the steps for one way to do this.

Create request and set a calback for BeginGetRequestStream

var request = (HttpWebRequest)WebRequest.Create(App.Config.ServerUris.Login);

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

In that callback, get the request stream and write your data to it.

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

Set a callback for the response from the server.

request.BeginGetResponse(ResponseCallback, request);

Check that everything worked OK on the server

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
            }
        }
    }
}

On the server you will need to deserialize the data and turn it back into an image as appropriate.

HTH.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文