Uploading files to remote server (with multiple parameters) – RestSharp

In this post I will explain how to, in an easy way, upload files to remote server using “POST” http method.

To accomplish uploading file to remote server, without additional parameters, we can use WebClient class, which is fairly easy to use, but for POST request where we send file and additional parameters we will have to use HttpWebRequest class which is quite complicated for this purpose, or, as in our case, use third-party libraries.

Some of the available libraries:

In this example we will use RestSharp.

Downloading RestSharp and adding DLL to project

You can download RestSharp from GitHub here or you can just download RestSharp DLL file for Windows Phone here.

To add RestSharp to your project Right click on References folder in you project and select Add reference, than Browse and find DLL file on your computer and select it.

 

How to use RestSharp class?

To use RestSharp class in our code we will have to add a using:

 using RestSharp; 

In this example i will send 2 parameters and 1 file to a remote server. Let’s say that server accepts naming of the files and parameters like these below:

Parameters: user_id, user_hash and files: photo.

And let’s say we want to upload captured photo from phone camera with parameters listed above. To make an async call to a our remote server with RestSharp, all code we need is this below:

     private void button1_Click(object sender, RoutedEventArgs e)
        {
            CameraCaptureTask cameraCapture = new CameraCaptureTask();
            cameraCapture.Completed += new EventHandler<PhotoResult>(cameraCapture_Completed);
            cameraCapture.Show();
        }

        void cameraCapture_Completed(object sender, PhotoResult e)
        {
            //checking if everything went fine when capturing a photo
            if (e.TaskResult != TaskResult.OK)
                return;

            string userId = "10";
            string userHash = "40a6fe73f24b4c73f0d7943c8a41adcb";

            //preparing RestRequest by adding server url, parameteres and files...
            RestRequest request = new RestRequest("http://www.myserver.com/upload.php", Method.POST);
            request.AddParameter("user_id", userId);
            request.AddParameter("user_hash", userHash);
            request.AddFile("photo", ReadToEnd(e.ChosenPhoto), "photo.jpg", "image/pjpeg");

            //calling server with restClient
            RestClient restClient = new RestClient();
            restClient.ExecuteAsync(request, (response) =>
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //upload successfull
                    MessageBox.Show("Upload completed succesfully...\n" + response.Content);
                }
                else
                {
                    //error ocured during upload
                    MessageBox.Show(response.StatusCode + "\n" + response.StatusDescription);
                }
            });
        }

        //method for converting stream to byte[]
        public 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;
            }
        }

Note:

Always check what kind of files remote server accepts. In our case we are simulating simple HTML file upload, file type that we are sending is image/pjpeg. HTML code that we are simulating is something like this:

 <form method='POST' enctype='multipart/form-data' action='http://www.myserver.com/upload.php'>
User id: <input type=text name=user_id><br>
User hash: <input type=text name=user_hash><br>

<br>
File to upload: <input type=file name=image><br>

<input type=submit value=Press> to upload the file!
</form> 

In case you have problems i recommend using Fiddler to see how web requests work and what is actually happening when we send request and recieve response.

Source code

Download source code here.

Advertisements

15 comments

  1. Pingback: Photo upload with parameters to a PHP page | PHP Developer Resource
  2. Pingback: Upload file through c# using JSON request and RestSharp
  3. Anonymous

    This is only client side tutorial. Upload.php is on the server, already created. Check stack overflow on how to create upload.php.

      • aandino22

        HERE IT IS THE UPLOAD.PHP
        0) {

        // Temporary file name stored on the server
        $tmpName = $_FILES[‘photo’][‘tmp_name’];

        // Read the file
        $fp = fopen($tmpName, ‘r’);
        $data = fread($fp, filesize($tmpName));
        $data = addslashes($data);
        fclose($fp);

        // Create the query and insert
        // into our database.
        $query = “INSERT INTO tbl_photos “;
        $query .= “(photo) VALUES (‘$data’)”;
        $results = mysql_query($query, $link);

        // Print results
        print “Thank you, your file has been uploaded.”;

        }
        else {
        print “No photo selected/uploaded”;
        }

        // Close our MySQL Link
        mysql_close($link);
        ?>

  4. aandino22

    kchaou Here it is the upload.php

    0) {

    // Temporary file name stored on the server
    $tmpName = $_FILES[‘photo’][‘tmp_name’];

    // Read the file
    $fp = fopen($tmpName, ‘r’);
    $data = fread($fp, filesize($tmpName));
    $data = addslashes($data);
    fclose($fp);

    // Create the query and insert
    // into our database.
    $query = “INSERT INTO tbl_photos “;
    $query .= “(photo) VALUES (‘$data’)”;
    $results = mysql_query($query, $link);

    // Print results
    print “Thank you, your file has been uploaded.”;

    }
    else {
    print “No photo selected/uploaded”;
    }

    // Close our MySQL Link
    mysql_close($link);
    ?>

  5. Pingback: what is the php code for retrieving file sent using windows phone 8 Restsharp
  6. Santosh

    Hi Guys.I am trying to upload recorded audio file to server using rest request but uploaded recorded file(Which i sent ) that file is not playing.so please help me to do this one.

  7. Pingback: what is the php code for retrieving file sent using windows phone 8 Restsharp - Technology

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s