WP7 - 带有图像的 POST 表单 [英] WP7 - POST form with an image

查看:16
本文介绍了WP7 - 带有图像的 POST 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将图像从 Windows Phone 7 发送到某些电子邮件地址.我使用这个类将文本值提交给一个 PHP 脚本,它解析数据并将格式化的电子邮件发送到地址.问题是我不知道如何将图像发送到该脚本,以将图像附加到电子邮件中.PHP 脚本可以以任何方式更改.如果我有一个 Image 对象,我该如何更改此类以允许发送图像?

I need to send an image from the Windows Phone 7 to some e-mail addresses. I use this class to submit text values to a PHP script, wich parses data and sends a formatted e-mail to the addresses. The problem is that I can't figure out how to send an image to that script, to attach the image to the e-mail. The PHP script can be changed in any way. If I have an Image object, how can I change this class to allow sending images?

public class PostSubmitter
{
    public string url { get; set; }
    public Dictionary<string, string> parameters { get; set; }

    public PostSubmitter() { }

    public void Submit()
    {
        // Prepare web request...
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";

        myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
    }

    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);

        // Prepare Parameters String
        string parametersString = "";
        foreach (KeyValuePair<string, string> parameter in parameters)
        {
            parametersString = parametersString + (parametersString != "" ? "&" : "") + string.Format("{0}={1}", parameter.Key, parameter.Value);
        }

        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(parametersString);
        // Write to the request stream.
        postStream.Write(byteArray, 0, parametersString.Length);
        postStream.Close();
        // Start the asynchronous operation to get the response
        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }

    private void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        // Close the stream object
        streamResponse.Close();
        streamRead.Close();
        // Release the HttpWebResponse
        response.Close();
        //Action<string> act = new Action<string>(DisplayResponse);
        //this.Dispatcher.BeginInvoke(act, responseString);
    }

我是这样使用这个类的:

I use the class in this way:

Dictionary<string, string> data = new Dictionary<string, string>()
{
        {"nom", nom.Text},
        {"cognoms", cognoms.Text},
        {"email", email.Text},
        {"telefon", telefon.Text}
};

PostSubmitter post = new PostSubmitter() { url = "http://example.com/parserscript.php", parameters = data };
post.Submit();

非常感谢!

推荐答案

我已将上面的代码转换为以下内容,我相信它会有所帮助:

I've converted the above code to the following, I'm sure it will help:

public class PostSubmitter
{
    public string url { get; set; }
    public Dictionary<string, object> parameters { get; set; }
    string boundary = "----------" + DateTime.Now.Ticks.ToString();

    public PostSubmitter() { }

    public void Submit()
    {
        // Prepare web request...
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
        myRequest.Method = "POST";
        myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

        myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
    }

    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        Stream postStream = request.EndGetRequestStream(asynchronousResult);

        writeMultipartObject(postStream, parameters);
        postStream.Close();

        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }

    private void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        streamResponse.Close();
        streamRead.Close();
        // Release the HttpWebResponse
        response.Close();
    }


    public void writeMultipartObject(Stream stream, object data)
    {
        StreamWriter writer = new StreamWriter(stream);
        if (data != null)
        {
            foreach (var entry in data as Dictionary<string, object>)
            {
                WriteEntry(writer, entry.Key, entry.Value);
            }
        }
        writer.Write("--");
        writer.Write(boundary);
        writer.WriteLine("--");
        writer.Flush();
    }

    private void WriteEntry(StreamWriter writer, string key, object value)
    {
        if (value != null)
        {
            writer.Write("--");
            writer.WriteLine(boundary);
            if (value is byte[])
            {
                byte[] ba = value as byte[];

                writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg");
                writer.WriteLine(@"Content-Type: application/octet-stream");
                //writer.WriteLine(@"Content-Type: image / jpeg");
                writer.WriteLine(@"Content-Length: " + ba.Length);
                writer.WriteLine();
                writer.Flush();
                Stream output = writer.BaseStream;

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

要将图像从相机转换为字节数组,我使用了以下方法:

To convert an image from the camera to an byte array I've used the follwing:

private void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            try
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.ChosenPhoto);
                foto.Source = image;

                using (MemoryStream ms = new MemoryStream())
                {
                    WriteableBitmap btmMap = new WriteableBitmap(image);

                    // write an image into the stream
                    Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, image.PixelHeight, 0, 100);

                    byteArray = ms.ToArray();
                }
            }
            catch (ArgumentNullException) { /* Nothing */ }
        }

我是这样使用这个类的:

And I use the class this way:

Dictionary<string, object> data = new Dictionary<string, object>()
        {
            {"nom", nom.Text},
            {"cognoms", cognoms.Text},
            {"email", email.Text},
            {"telefon", telefon.Text},
            {"comentari", comentari.Text},
            {"foto", byteArray},
        };
        PostSubmitter post = new PostSubmitter() { url = "http://example.com/parserscript.php", parameters = data};
        post.Submit();

我不知道这是否是将图像从手机发送到服务器的最佳方式,但我找不到任何东西,所以我创建了自己的课程,只是阅读这个和那个,这花了我好几个天.如果有人想改进代码或写任何评论,将受到欢迎.

I don't know if it's the best way to send an image from the phone to a server, but I couldn't find anything, so I made my own class just reading this and that, and it has taken me several days. If anybody wants to improve the code or write any comment will be welcomed.

这篇关于WP7 - 带有图像的 POST 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆