August
14
2007
1:23 pm
Tags:
Post Meta :
You Diggin?

Level: Beginner (coder)

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:

<?php
$uploaddir
= ‘upload/’; // Relative Upload Location of data file

if (is_uploaded_file($_FILES[‘file’][‘tmp_name’])) {
$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. “;
}

else
print_r($_FILES);
}

else {
echo “Upload Failed!!!”;
print_r($_FILES);
}
?>

and this is the C# code:


System.Net.WebClient Client = new System.Net.WebClient ();
Client.Headers.Add("Content-Type","binary/octet-stream");
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’m testing with an image file, im 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 google! Let me know if you got any questions,

Happy Coding :)

 


September
15
2007
10:26 pm
Type:
Comment

Thanks :D great tutorial, I don’t know how to work with C# yet, so I converted the code to VB.NET and I’ll try it tomorrow.

February
21
2008
9:15 pm
Type:
Comment
Tema

Thanks for code, but it seems like your blog autoformat tool spoils php code with wrong quotes.

March
8
2008
1:44 am
Type:
Comment
admin

Thank you Tema, I’ll try to fix that in the coming few days.

August
3
2008
9:23 pm
Type:
Comment

Wow, amazing. After days and days of searching, I stumble upon some code that actually works. Thanks!!

August
8
2008
5:03 am
Type:
Comment
admin

Glad it helped u out Mat :D

Participate! Leave your comment.