Hello There, Guest!
View New Posts  |  View Today's Posts
[Source] C# Upload File (Async) to PHP endpoint (PHP code included)

  • 0 Vote(s) - 0 Average


04-29-2014, 12:00 PM #1
KoBE
¯\_(ツ)_/¯
******
Global Moderators
Posts: 4,862 Threads:494 Joined: Jun 2011 Reputation: 67

C# Upload File (Async) to PHP endpoint (PHP code included)
Hey guys,

There hasn't been much content posted lately so I'll post something I wrote the other day for a project.

Basically, this is a very simple way to upload a file to a PHP file. In this example I use a Text File but it can be easily modified to allow other types of files as well.

C# Code
Code:
string endPoint = "http://YOUR_URL/upload.php";
string filePath = "log.txt";

WebClient wc = new WebClient();

// fired when upload progress is changed
// this updates a progressbar named pbProgress
wc.UploadProgressChanged += (o, ea) =>
{
    if (ea.ProgressPercentage >= 0 && ea.ProgressPercentage <= 100)
        pbProgress.Value = ea.ProgressPercentage;
};

// fired when the file upload is complete
// fired if an error occurs or if it's successful
wc.UploadFileCompleted += (o, ea) =>
{
    // determine if upload failed or not
    if (ea.Error == null)
    {
        // response will let us know if there
        // was an error on the PHP side
        string response = Encoding.UTF8.GetString(ea.Result);
        if (response == "Success")
            lblStatus.Text = "Upload Complete.";
        else
        {
            lblStatus.Text = "Upload Failed.";
            MessageBox.Show(response);
        }
    }
    else
    {
        lblStatus.Text = "Upload Failed.";
        MessageBox.Show(ea.Error.Message);
    }
};

// set the status to Uploading
lblStatus.Text = "Uploading...";

// tell the webclient to upload the file
wc.UploadFileAsync(new Uri(endPoint), filePath);

PHP code (updated by Ace):
PHP Code:
<?php

// grab the extension
$ext pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

// validate the extension
if (strcasecmp($ext'txt') != 0) {
  echo 
"Error: Invalid filetype: {$ext}";
  exit();
}

if (
$_FILES['file']['error'] > 0)
{
  echo 
"Error: Code {$_FILES['file']['error']}";
  exit();
}

// create a unique name for the log file
$target 'logs/log'.time().'.txt';

// move the uploaded file to it's new path
move_uploaded_file($_FILES['file']['tmp_name'], $target);

// verify that the file was moved
if(file_exists($target)) 
  echo 
'Success';
else 
  echo 
'Error: Unable to save file';

?>
This post was last modified: 05-01-2014, 01:13 PM by KoBE.

04-29-2014, 12:02 PM #2
KoBE
¯\_(ツ)_/¯
******
Global Moderators
Posts: 4,862 Threads:494 Joined: Jun 2011 Reputation: 67

RE: C# Upload File (Async) to PHP endpoint (PHP code included)
Keep in mind this is a very simple example and is not meant to be anything crazy. I needed something quick and simple and this is what I came up with.

If anyone has any questions feel free to post them.

04-30-2014, 04:59 PM #3
AceInfinity
Developer
*******
Administrators
Posts: 9,733 Threads:1,026 Joined: Jun 2011 Reputation: 76

RE: C# Upload File (Async) to PHP endpoint (PHP code included)
I'd re-write the PHP code like this:
PHP Code:
<?php

// grab the extension
$ext pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

// validate the extension
if (strcasecmp($ext'txt') != 0) {
  echo 
"Error: Invalid filetype: {$ext}";
  exit();
}

if (
$_FILES['file']['error'] > 0)
{
  echo 
"Error: Code {$_FILES['file']['error']}";
  exit();
}

// create a unique name for the log file
$target 'logs/log'.time().'.txt';

// move the uploaded file to it's new path
move_uploaded_file($_FILES['file']['tmp_name'], $target);

// verify that the file was moved
if(file_exists($target)) echo 'Success';
else echo 
'Error: Unable to save file';

?>

Case insensitive comparison (just in case), and single quotes where double isn't needed, along with removing some of the nested code. You can use pathinfo() to grab the extension though.

Cool idea :)
This post was last modified: 04-30-2014, 05:04 PM by AceInfinity.


Microsoft MVP .NET Programming - (2012 - Present)
®Crestron DMC-T Certified Automation Programmer

Development Site: aceinfinity.net

 ▲
 ▲ ▲

05-01-2014, 01:11 PM #4
KoBE
¯\_(ツ)_/¯
******
Global Moderators
Posts: 4,862 Threads:494 Joined: Jun 2011 Reputation: 67

RE: C# Upload File (Async) to PHP endpoint (PHP code included)
That PHP code does look a lot cleaner. I was in a hurry to get the functionality put in. I'll update the OP with your version.




Forum Jump:


Possibly Related Threads...
Thread Author Replies Views Last Post
Star  Multi-Client Server Async Socket Example KoBE 165 168,113 09-10-2016, 05:17 AM
Last Post: R4TK3N
   Code VB net not work MrChuCong 2 1,451 07-17-2015, 09:08 AM
Last Post: xflick13
  Save to text file jimmy341 5 2,563 05-14-2015, 07:35 PM
Last Post: AceInfinity
  calling javascript function from code behind redhonda9834 1 1,103 04-02-2015, 04:00 PM
Last Post: KoBE
  Async Gizmag Client AceInfinity 7 3,514 02-21-2015, 11:50 PM
Last Post: AceInfinity


Users browsing this thread: 1 Guest(s)