2010-05-08 53 views
5

傢伙,首先感謝您的貢獻,我在這裏找到了很好的迴應。然而,我遇到了一個我無法解決的問題,如果有人能提供任何幫助,我們將不勝感激。如何模擬瀏覽器文件上傳與HttpWebRequest

我正在用C#開發這個應用程序,可以將圖像從計算機上傳到用戶photoblog。爲此,我想爲主要用PHP編寫的photoblogs平臺pixelpost

我在這裏和其他網頁上搜索過,但在那裏提供的實例並沒有爲我工作。 (Upload files with HTTPWebrequest (multipart/form-data)) 和 (http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code) 一旦準備就緒,我將在互聯網上免費提供它,也許還會創建它的Windows移動版本,因爲我是一個pixelpost的粉絲。

這裏是我使用的代碼:

 string formUrl = "http://localhost/pixelpost/admin/index.php?x=login"; 
     string formParams = string.Format("user={0}&password={1}", "user-String", "password-String"); 
     string cookieHeader; 
     HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl); 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.Method = "POST"; 
     req.AllowAutoRedirect = false; 
     byte[] bytes = Encoding.ASCII.GetBytes(formParams); 
     req.ContentLength = bytes.Length; 
     using (Stream os = req.GetRequestStream()) 
     { 
      os.Write(bytes, 0, bytes.Length); 
     } 
     HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
     cookieHeader = resp.Headers["Set-Cookie"]; 

     string pageSource; 
     using (StreamReader sr = new StreamReader(resp.GetResponseStream())) 
     { 
      pageSource = sr.ReadToEnd(); 
      Console.WriteLine(); 
     } 

     string getUrl = "http://localhost/pixelpost/admin/index.php"; 
     HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl); 
     getRequest.Headers.Add("Cookie", cookieHeader); 
     HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse(); 
     using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) 
     { 
      pageSource = sr.ReadToEnd(); 
     } 

     // end first part: login to admin panel 

     long length = 0; 
     string boundary = "----------------------------" + 
     DateTime.Now.Ticks.ToString("x"); 

     HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save"); 
     httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary; 
     httpWebRequest2.Method = "POST"; 
     httpWebRequest2.AllowAutoRedirect = false; 
     httpWebRequest2.KeepAlive = false; 
     httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials; 
     httpWebRequest2.Headers.Add("Cookie", cookieHeader); 



     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 formitem = string.Format(formdataTemplate, "headline", "image-name"); 
     byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); 
     memStream.Write(formitembytes, 0, formitembytes.Length); 

     memStream.Write(boundarybytes, 0, boundarybytes.Length); 


     string headerTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; 



     string header = string.Format(headerTemplate, "userfile", "path-to-the-local-file"); 

     byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); 

     memStream.Write(headerbytes, 0, headerbytes.Length); 


     FileStream fileStream = new FileStream("path-to-the-local-file", 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(); 


     httpWebRequest2.ContentLength = memStream.Length; 

     Stream requestStream = httpWebRequest2.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(); 


     WebResponse webResponse2 = httpWebRequest2.GetResponse(); 

     Stream stream2 = webResponse2.GetResponseStream(); 
     StreamReader reader2 = new StreamReader(stream2); 


     Console.WriteLine(reader2.ReadToEnd()); 

     webResponse2.Close(); 
     httpWebRequest2 = null; 
     webResponse2 = null; 

而且這裏是PHP: (http://dl.dropbox.com/u/3149888/index.php) 和 (http://dl.dropbox.com/u/3149888/new_image.php

必填字段是標題 userfile所以我找不出錯誤在哪裏,正如發送的格式正確。我猜測發送到表單的八位字節流有問題。 也許這是一個愚蠢的錯誤,我無法追查,無論如何,如果你能幫助我,這將意味着很多。

感謝,

+1

登錄是否正常工作,您收回cookie嗎? – 2010-05-08 23:49:51

+1

什麼是沒有關於它的工作? – 2010-05-08 23:50:17

+0

是的,登錄工作一切正常。我找回cookie,如果我在控制檯中顯示pageSource字符串,在「//結束第一部分:登錄到管理面板」之前,它包含管理面板的HTML代碼。對於第二個請求,當我發送所有表單數據和文件八位字節流時​​,我只能將標題設置爲'image-name'的「Submit」頁面取回HTML,並且沒有圖像上傳到博客。 所以,基本上我無法上傳圖像。通常,如果出現問題,我應該收到一條錯誤消息,而不是使用設置了標題的HTML。 – cucicov 2010-05-09 07:53:49

回答

5

所以馬丁幫我在這裏,我能夠做以上面的代碼中的重要變化它才能正常工作。 Content-Type必須更改爲image/jpeg。我也用C#Image類型來發送圖像流。

還要注意流格式,因爲它不必包含多餘的空格或新行。

這裏是改變部分:

 string formUrl = "http://localhost/pixelpost/admin/index.php?x=login"; 
     string formParams = string.Format("user={0}&password={1}", "username", "password"); 
     string cookieHeader; 
     HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl); 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.Method = "POST"; 
     req.AllowAutoRedirect = false; 
     byte[] bytes = Encoding.ASCII.GetBytes(formParams); 
     req.ContentLength = bytes.Length; 
     using (Stream os = req.GetRequestStream()) 
     { 
      os.Write(bytes, 0, bytes.Length); 
     } 
     HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
     cookieHeader = resp.Headers["Set-Cookie"]; 

     string pageSource; 
     using (StreamReader sr = new StreamReader(resp.GetResponseStream())) 
     { 
      pageSource = sr.ReadToEnd(); 
     } 

     string getUrl = "http://localhost/pixelpost/admin/index.php"; 
     HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl); 
     getRequest.Headers.Add("Cookie", cookieHeader); 
     HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse(); 
     using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) 
     { 
      pageSource = sr.ReadToEnd(); 
     } 


     long length = 0; 
     string boundary = "----------------------------" + 
     DateTime.Now.Ticks.ToString("x"); 

     HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save"); 
     httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary; 
     httpWebRequest2.Method = "POST"; 
     httpWebRequest2.AllowAutoRedirect = false; 
     httpWebRequest2.KeepAlive = false; 
     httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials; 
     httpWebRequest2.Headers.Add("Cookie", cookieHeader); 

     Stream memStream = new System.IO.MemoryStream(); 

     byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary); 


     string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg\r\n\r\n"; 



     string header = string.Format(headerTemplate, "userfile", "Sunset.jpg"); 



     byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header); 

     memStream.Write(headerbytes, 0, headerbytes.Length); 


     Image img = null; 
     img = Image.FromFile("C:/Documents and Settings/Dorin Cucicov/My Documents/My Pictures/Sunset.jpg", true); 
     img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg); 


     memStream.Write(boundarybytes, 0, boundarybytes.Length); 


     string formdataTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; 

     string formitem = string.Format(formdataTemplate, "headline", "Sunset"); 
     byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); 
     memStream.Write(formitembytes, 0, formitembytes.Length); 

     memStream.Write(boundarybytes, 0, boundarybytes.Length); 


     httpWebRequest2.ContentLength = memStream.Length; 

     Stream requestStream = httpWebRequest2.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(); 


     WebResponse webResponse2 = httpWebRequest2.GetResponse(); 

     Stream stream2 = webResponse2.GetResponseStream(); 
     StreamReader reader2 = new StreamReader(stream2); 


     Console.WriteLine(reader2.ReadToEnd()); 

     webResponse2.Close(); 
     httpWebRequest2 = null; 
     webResponse2 = null; 

再次感謝大家的回答或者只是閱讀。