WP7 - POST form with an image

前端 未结 3 1376
悲&欢浪女
悲&欢浪女 2020-12-28 10:33

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

相关标签:
3条回答
  • 2020-12-28 11:13

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-28 11:16

    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

    0 讨论(0)
  • 2020-12-28 11:37

    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.

    0 讨论(0)
提交回复
热议问题