2013-04-01 78 views
19

我有一個小型的C#web應用程序。如何獲取允許用戶通過HTTP POST發送文件的c#代碼。它應該能夠發送文本文件,圖像文件,excel,csv ,doc(所有類型的文件),而不使用流讀取器和所有。在c#中使用HTTP POST發送文件

+0

http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data –

+2

'我已經試過各種方法,但沒有人幫助我。 ' - 如果你展示了一些你已經嘗試過的方法,我們可能會發現他們有什麼問題。現在,很難進行建設性的討論。 –

+1

重複[使用C#通過HTTP POST發送文件](http://stackoverflow.com/questions/1131425/send-a-file-via-http-post-with-c-sharp)和其他各種。顯示你曾經嘗試過的,以及upvoters,請考慮你是upvoting的問題是一個受歡迎的除了網站或只是一個副本。 – CodeCaster

回答

12

你可以試試下面的代碼:

public void PostMultipleFiles(string url, string[] files) 
{ 
    string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); 
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; 
    httpWebRequest.Method = "POST"; 
    httpWebRequest.KeepAlive = true; 
    httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; 
    Stream memStream = new System.IO.MemoryStream(); 
    byte[] boundarybytes =System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary  +"\r\n"); 
    string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; 
    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; 
    memStream.Write(boundarybytes, 0, boundarybytes.Length); 
    for (int i = 0; i < files.Length; i++) 
    { 
     string header = string.Format(headerTemplate, "file" + i, files[i]); 
     //string header = string.Format(headerTemplate, "uplTheFile", files[i]); 
     byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); 
     memStream.Write(headerbytes, 0, headerbytes.Length); 
     FileStream fileStream = new FileStream(files[i], FileMode.Open, 
     FileAccess.Read); 
     byte[] buffer = new byte[1024]; 
     int bytesRead = 0; 
     while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) 
     { 
      memStream.Write(buffer, 0, bytesRead); 
     } 
     memStream.Write(boundarybytes, 0, boundarybytes.Length); 
     fileStream.Close(); 
    } 
    httpWebRequest.ContentLength = memStream.Length; 
    Stream requestStream = httpWebRequest.GetRequestStream(); 
    memStream.Position = 0; 
    byte[] tempBuffer = new byte[memStream.Length]; 
    memStream.Read(tempBuffer, 0, tempBuffer.Length); 
    memStream.Close(); 
    requestStream.Write(tempBuffer, 0, tempBuffer.Length); 
    requestStream.Close(); 
    try 
    { 
     WebResponse webResponse = httpWebRequest.GetResponse(); 
     Stream stream = webResponse.GetResponseStream(); 
     StreamReader reader = new StreamReader(stream); 
     string var = reader.ReadToEnd(); 

    } 
    catch (Exception ex) 
    { 
     response.InnerHtml = ex.Message; 
    } 
    httpWebRequest = null; 
} 
+14

只是傾銷50行代碼不是答案。這個問題有很多答案,許多這樣的代碼已經內置在.NET類型中,比如WebClient和HttpClient。 – CodeCaster

+0

你能解釋一下接收者頁面的檢索過程嗎? –

+1

你可以舉一個URL的例子.. 它包含文件名嗎? –

8

試試這個

string fileToUpload = @"c:\user\test.txt"; 
string url = "http://example.com/upload"; 
using (var client = new WebClient()) 
{ 
byte[] result = client.UploadFile(url, fileToUpload); 
string responseAsString = Encoding.Default.GetString(result); 
} 
9

使用.NET 4.5(或通過添加的NuGet的Microsoft.Net.Http包.NET 4.0)有一個更簡單的方法模擬表單請求。這裏有一個例子:

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes) 
{ 
    HttpContent stringContent = new StringContent(paramString); 
    HttpContent fileStreamContent = new StreamContent(paramFileStream); 
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes); 
    using (var client = new HttpClient()) 
    using (var formData = new MultipartFormDataContent()) 
    { 
     formData.Add(stringContent, "param1", "param1"); 
     formData.Add(fileStreamContent, "file1", "file1"); 
     formData.Add(bytesContent, "file2", "file2"); 
     var response = client.PostAsync(actionUrl, formData).Result; 
     if (!response.IsSuccessStatusCode) 
     { 
      return null; 
     } 
     return response.Content.ReadAsStreamAsync().Result; 
    } 
} 
+0

是否必須始終使用多部分表單數據? – Abhijeet

相關問題