2014-01-05 42 views
2

考慮下面的HTML代碼後二進制數據從控制檯應用程序

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

現在我需要實現這個使用C#。 我有一個字節數組中的文件。

byte[] data; 
String fileName; 

那麼,我該如何做到這一點。我想我必須創建一個合適的HTTP POST請求。但是如何? 我試過使用HttpWebRequest類。但不知道如何繼續。

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

注意:文件'upload.php'與HTML代碼完美協作。

+0

[.NET的可能重複:用數據發送POST和讀取響應的最簡單方法](http: //www.stackoverflow.com/questions/4088625/net-simplest-way-to-send-post-with-data-and-read-response) – Shai

+0

沒有。他們沒有發佈二進制數據。 –

回答

0

make文件上傳控件爲RUNAT服務器和嘗試下面的代碼

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(); 
} 

更新

// 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(); 
+0

從現在開始,我正在使用基於控制檯的應用程序。無法使用上傳控件。 –

+0

它不會在控制檯app.Check我更新的答案 –

+0

那麼如何通過HTTP POST使用控制檯應用程序發送二進制數據。我有一個字節數組中的文件。 –

相關問題