|
w00t, our first c# and PHP tutorial =0)
I'm new to c# and .net alltogether and therefor I thought it would
be a good idea to write about what i learn along with time, please
feel free to comment if you find something wrong, or have any
questions regarding the code...
Today I learned on how to upload a file using C# to a PHP server.
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.
Quote this article on your site
Powered by AkoComment Tweaked v.1.4.2 |