I was fed up with uploading the attachments using FTP as it was too slow (and vulnerable too), maintaining credentials to connect to server, managing permissions to specific folder etc. and all that nasty stuff. Clients have also complained on this. After head-scratching and wall banging efforts, I planned to search for an alternative for FTP to upload the files. Found this way… Its pretty cool and uploading files much faster compared to FTP approach. Just wanted to share it with you, hoping that it may help someone who are in need!
This is a small tutorial which will teach you how to upload files using a C# client application to a server running PHP.
We’ll call the PHP Script “upload.php”, this is what it should contain:
$uploaddir = ‘upload/’; // Relative Upload Location of data file
$uploadfile = $uploaddir . basename($_FILES[‘file’][‘name’]);
echo “File “. $_FILES[‘file’][‘name’] .” uploaded successfully. “;
if (move_uploaded_file($_FILES[‘file’][‘tmp_name’], $uploadfile))
echo “File is valid, and was successfully moved. “;
echo “Upload Failed!!!”;
and here is the C# code…
System.Net.WebClient Client = new System.Net.WebClient ();
byte result = Client.UploadFile (“http://your_server/upload.php”,”POST”,”C:test.jpg”);
String s = System.Text.Encoding .UTF8 .GetString (result,0,result.Length );
In the C# part, replace “your_server.com” with your server, also notice that this is a test code, it will upload c:\test.jpg, because I am testing with an image file, I am using the header “binary/octet-stream” as it works with all files (image, txt, etc)…
Hope this helps someone out there as I couldn’t find any tutorials about this specific matter on googling!