4

I am trying to upload a picture from the Pictures Library (on WP7) and save it in a folder on the server.

On the server, I'm using PHP to receive the file using POST Method. The PHP Code is:

<?php
$uploads_dir = 'files/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>

I've already tried some approaches, but they all just seem to fail. I've already done this job in a Windows Forms application using the Client.UploadFile method but it seems that it cannot be used on a Windows Phone Application.

I think httpwebrequest can help, right?

This is my C# code so far:

public partial class SamplePage : PhoneApplicationPage
    {
        public SamplePage()
        {
            InitializeComponent();
        }

        PhotoChooserTask selectphoto = null;

        private void SampleBtn_Click(object sender, RoutedEventArgs e)
        {
            selectphoto = new PhotoChooserTask();
            selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
            selectphoto.Show();
        }

        void selectphoto_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BinaryReader reader = new BinaryReader(e.ChosenPhoto);
                image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
                txtBX.Text = e.OriginalFileName;
            }
        }
    }

I read it somewhere that the image is required to be converted to a string of bytes, I don't know for sure. But, please help me.

Thanks a lot in advance.

Shrayansh Sharma
  • 217
  • 1
  • 5
  • 16

1 Answers1

4

I would convert the image to base64 (see System.Convert) then transfer via POST:

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://mydomain.cc/saveimage.php");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string postData = String.Format("image={0}", myBase64EncodedImage);   

            // Getting the request stream.
            request.BeginGetRequestStream
                (result =>
                {
                    // Sending the request.
                    using (var requestStream = request.EndGetRequestStream(result))
                    {
                        using (StreamWriter writer = new StreamWriter(requestStream))
                        {
                            writer.Write(postData);
                            writer.Flush();
                        }
                    }

                    // Getting the response.
                    request.BeginGetResponse(responseResult =>
                    {
                        var webResponse = request.EndGetResponse(responseResult);
                        using (var responseStream = webResponse.GetResponseStream())
                        {
                            using (var streamReader = new StreamReader(responseStream))
                            {
                                string srresult = streamReader.ReadToEnd();
                            }
                        }
                    }, null);
                }, null);
        }

saveimage.php should look like this:

<?
function base64_to_image( $imageData, $outputfile ) {
    /* encode & write data (binary) */
    $ifp = fopen( $outputfile, "wb" );
    fwrite( $ifp, base64_decode( $imageData ) );
    fclose( $ifp );
    /* return output filename */
    return( $outputfile );
}       

if (isset($_POST['image'])) {
    base64_to_jpeg($_POST['image'], "my_path_to_store_images.jpg");
}
else
    die("no image data found");
?>

Note: I have not tested the code. There might be typos or other errors. It's just to illustrate how I would transfer an image using POST.

Edit as a repy to your comment: I don't have code to encode to base64 at hand but here is how you would decode a base64 encoded image in C#:

byte[] image = Convert.FromBase64String(str);
thomiel
  • 2,467
  • 22
  • 37
  • Hey, thanks a lot! This is exactly what I was looking for. However, I'm not able to convert the image to base64. Can you please help me with the appropriate code. I'll be very grateful to you!!! :-) – Shrayansh Sharma Mar 20 '13 at 13:09
  • You've helped me a lot. Thank you very much. I'm still looking to encode it to base64, however. :-) Thanks, anyway. – Shrayansh Sharma Mar 21 '13 at 00:59
  • 1
    Come on, it's not that hard... ok, the function is called ToBase64String. Wasn't too had, was it? ;) – thomiel Mar 21 '13 at 15:49
  • Yeah, I knew that already. But, the function ToBase64String does not accepts image as parameter. That's the problem. – Shrayansh Sharma Mar 21 '13 at 16:15
  • I am still stuck at base64 encoding. Can you please assist me? – Shrayansh Sharma Mar 22 '13 at 02:00
  • Sure, you cannot use an image object directly. You need to get the image in a byte array the same way it is stored in the file system. – thomiel Mar 22 '13 at 09:10
  • Hey, I'm extremely sorry if I'm bugging you. But, can you please help me to convert the image into a byte array - because that's the exact point where I'm stuck. And, you see, I'm really trying to do this for so many days now - and still no good result! Please help me. – Shrayansh Sharma Mar 27 '13 at 06:38
  • Thanks a lot!!! By the way, I'm now using RestSharp Library to upload pictures along with parameters. Thank you very much for the help, anyway. – Shrayansh Sharma Mar 27 '13 at 23:48