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
Thanks
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.
Thanks for code, but it seems like your blog autoformat tool spoils php code with wrong quotes.
Thank you Tema, I’ll try to fix that in the coming few days.
Wow, amazing. After days and days of searching, I stumble upon some code that actually works. Thanks!!
Glad it helped u out Mat
Thanks you , i have question , can you descript what code c# will doing,
s what will get. if was $_FILES is array.
thx
Thanx , I have already used this code, but my problem is that,I have php code ready for handle the upload on server side. And it is bit same as your code, the only difference is my php page use $_FILE['image'] instead of $_FILES[‘file’].So, can you help me how can I achieve this? I mean what are the changes required on C# code? From C# can I send image file with header as “image”? Please help me. Thanx in advance.
It is great ……….
Thank you very much for that code.
Just what i was looking for :thumbsup:
Please write the same tutorial for c# CF and php
Pingback: Upload using C++ as Client and PHP as Server | johny.org