WP7 - POST form with image

I need to send an image from Windows Phone 7 to some email addresses. I use this class to send text values ​​to a PHP script that parses data and sends a formatted email to addresses. The problem is that I cannot figure out how to send the image to this script in order to attach the image to email. PHP script can be changed in any way. If I have an Image object, how can I modify 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 as follows:

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

Many thanks!

+6
source share
3 answers

I have converted the above code to the following, I am sure this 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 the image from the camera to an array of bytes, I used the following:

 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 as follows:

 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 this is the best way to send the image from the phone to the server, but I couldn’t find anything, so I made my own class just by reading this and this, and it took me a few days. If anyone wants to improve the code or write a comment would be welcome.

+14
source

There are many questions / answers here to help already

eg. Message from WebRequest - although I couldn’t pinpoint the photos.

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

eg. if you look at Hammock, you will find others who sent images directly from the camera to tumblr - see http://hammock.codeplex.com/discussions/235650

0
source

The above code works fine. I just use another method to convert the file to an array of bytes, which works great 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; } } } 
0
source

Source: https://habr.com/ru/post/885659/


All Articles