views:

336

answers:

2

I need to upload a file to my webserver from a C# program. The problem is, I need to also POST two strings at the same time. So far, I have:

            HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://localhost/test.php");             
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "&name=Test";
            postData += "&[email protected]";
            postData += "&file=file.txt";

            byte[] data = encoding.GetBytes(postData);

            HttpWReq.Method = "POST";    
            HttpWReq.ContentType = "application/x-www-form-urlencoded";   
            HttpWReq.ContentLength = data.Length;    
            Stream newStream = HttpWReq.GetRequestStream();


            newStream.Write(data, 0, data.Length);
            newStream.Close();

Here's the HTML and PHP:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
echo (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path) ? "Success!" : "Failed");
?>
<form enctype="multipart/form-data" action="test.php" method="POST">
Name : <input type="text" name="name"><br />
Email : <input type="text" name="email"><br />
File : <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Being Upload" />
</form>

I don't know where to add the file field though :\ Any help would be appreciated!

A: 

Maybe try add FileUpload Class from MSDN, or use CURL in your project.

Jasmin25
Well, anyways, I don't know how to upload them in the same form. For example, if I use the FileUpload method, it Uploads the file, then it submits the rest of them form... I want to do it all at the same time... Ha, i'm not sure if that makes sense :\
Kevin
+1  A: 

Notice that your HTML snippet in the PHP file correctly has enctype="multipart/form-data" in the <form> element, when your form submission includes a file upload it has to use the multipart/form-data content type or another multipart MIME type, but in your C# code you set the HTTP request ContentType to application/x-www-form-urlencoded. That content type won't support file submissions. The file uploaded has to be a separate part in the MIME message the form submission is.

I can't provide a code example because I'm not versed in C# or .NET in general, but I believe there should be a class to construct such messages, it might be in something seemingly related to e-mail handling.

nielsm