WP7 - 带图像的 POST 表单

发布于 2024-10-31 08:11:58 字数 2789 浏览 3 评论 0原文

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

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

我是这样使用这个类的:

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

Thank you very much!

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

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

发布评论

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

评论(3

百变从容 2024-11-07 08:11:58

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

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

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

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

并且我以这种方式使用该类:

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'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.

恋竹姑娘 2024-11-07 08:11:58

这里有很多问题/答案可以提供帮助,

例如
使用 WebRequest 发布 - 尽管我找不到任何专门用于照片的内容。

也许最好的方法是在 Codeplex 上使用类似 Hammock 的东西 - http://hammock.codeplex.com/ - 或者可能类似于 RESTSharp - http://restsharp.org/ - 它们提供标准的 REST POST 功能。

例如,如果您查看 Hammock,您会发现其他人直接从相机将图像发布到 tumblr - 请参阅 http://hammock.codeplex.com/discussions/235650

There are lots of questions/answers on here to help already

e.g.
Post with WebRequest - although i couldn't spot any specifically for photos.

Perhaps the best way is to use something like Hammock on Codeplex - http://hammock.codeplex.com/ - or perhaps something like RESTSharp - http://restsharp.org/ - they provide standard REST POST functions.

e.g. if you look within Hammock, then you'll find others who've posted images direct from the camera to tumblr - see http://hammock.codeplex.com/discussions/235650

眼眸里的那抹悲凉 2024-11-07 08:11:58

上面的代码完美运行。我只是使用不同的方法将文件转换为与音频完美配合的字节数组

public static class FileHelper
{
    public static byte[] ReadToEnd(System.IO.Stream stream)
    {
        long originalPosition = stream.Position;
        stream.Position = 0;

        try
        {
            byte[] readBuffer = new byte[4096];

            int totalBytesRead = 0;
            int bytesRead;

            while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
            {
                totalBytesRead += bytesRead;

                if (totalBytesRead == readBuffer.Length)
                {
                    int nextByte = stream.ReadByte();
                    if (nextByte != -1)
                    {
                        byte[] temp = new byte[readBuffer.Length * 2];
                        Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                        Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                        readBuffer = temp;
                        totalBytesRead++;
                    }
                }
            }

            byte[] buffer = readBuffer;
            if (readBuffer.Length != totalBytesRead)
            {
                buffer = new byte[totalBytesRead];
                Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
            }
            return buffer;
        }
        finally
        {
            stream.Position = originalPosition;
        }
    }
}

The above code works perfect. I just use a different method to convert the file to an array of bytes which works perfect with Audio

public static class FileHelper
{
    public static byte[] ReadToEnd(System.IO.Stream stream)
    {
        long originalPosition = stream.Position;
        stream.Position = 0;

        try
        {
            byte[] readBuffer = new byte[4096];

            int totalBytesRead = 0;
            int bytesRead;

            while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
            {
                totalBytesRead += bytesRead;

                if (totalBytesRead == readBuffer.Length)
                {
                    int nextByte = stream.ReadByte();
                    if (nextByte != -1)
                    {
                        byte[] temp = new byte[readBuffer.Length * 2];
                        Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                        Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                        readBuffer = temp;
                        totalBytesRead++;
                    }
                }
            }

            byte[] buffer = readBuffer;
            if (readBuffer.Length != totalBytesRead)
            {
                buffer = new byte[totalBytesRead];
                Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
            }
            return buffer;
        }
        finally
        {
            stream.Position = originalPosition;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文