abhinav pandey
abhinav pandey

Reputation: 584

Post Binary Data from console app

Consider the following HTML code

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
</form>

Now I need to implement this using c#. I have the file in a byte array.

byte[] data;
String fileName;

So how do I do this. I think I have to create a suitable HTTP POST request . But how? I tried using the HttpWebRequest class. But don't know how to proceed.

HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost/cs.php");
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";

Note : The file 'upload.php' is working perfectly with the HTML code.

Upvotes: 4

Views: 12157

Answers (2)

vtortola
vtortola

Reputation: 35905

You can use System.Net.WebClient:

using(WebClient client = new WebClient()) {
    client.UploadFile(address, filePath);
}

Upvotes: 1

santosh singh
santosh singh

Reputation: 28652

make file upload control as runat server and try following code

int contentLength = fileUpload.PostedFile.ContentLength;
byte[] data = new byte[contentLength];
fileUpload.PostedFile.InputStream.Read(data, 0, contentLength);

// Prepare web request...
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost/cs.php");
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data";
webRequest.ContentLength = data.Length;
using (Stream postStream = webRequest.GetRequestStream())
{
    // Send the data.
    postStream.Write(data, 0, data.Length);
    postStream.Close();
 }

Update

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://localhost/cs.php ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.

byte[] byteArray = data;
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

Upvotes: 3

Related Questions