我正嘗試使用.NET/C#將文件和一些參數發送到我的站點。閱讀了一些可以做幾個參數或者一個文件的教程後,我試圖將它們結合起來失敗。這裏是我嘗試這樣做:帶有文件和參數的WebRequest POST
WebRequest req = WebRequest.Create(baseURL + "upload");
req.Credentials = new NetworkCredential(username, password);
String boundary = "B0unD-Ary";
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.Method = "POST";
((HttpWebRequest)req).UserAgent = "UploadTester v0.1";
string postData = "--" + boundary + "\nContent-Disposition: form-data\n";
postData += "myId=123&someFk=456";
postData += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"file\" filename=\"upload.pdf\" Content-Type: application/pdf\n\n";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
byte[] filedata = null;
using (BinaryReader reader = new BinaryReader(File.OpenRead("myfile.pdf")))
filedata = reader.ReadBytes((int)reader.BaseStream.Length);
req.ContentLength = byteArray.Length + filedata.Length;
req.GetRequestStream().Write(byteArray, 0, byteArray.Length);
req.GetRequestStream().Write(filedata, 0, filedata.Length);
WebResponse response = req.GetResponse();
Stream data = response.GetResponseStream();
StreamReader sReader = new StreamReader(data);
String sResponse = sReader.ReadToEnd();
response.Close();
當我執行它,我得到一個500例外,說:「頭一節有超過10240個bnytes(也許它不能正常終止)」和Wireshark通知我,發送的請求是格式不正確的包,MIME multipart格式不正確。
可能有幾個問題在這裏,所以請讓我知道所有你能發現的問題
更新:以MIME從C#/。NET分開,我已經催生了一個線程在這裏:https://stackoverflow.com/questions/1880002/error-in-mime-packet-for-http-post
更新2:因此,後端的內容長度確實存在問題,即可用於讀取的字節數量小於所述的內容長度。但!如果我相應地減少了req.ContentLength中的內容長度,那麼我沒有足夠大的緩衝區大小來發送數據。有什麼建議麼?
更新3:事實上,它看起來像頭有一個過大的尺寸相比,它包含的數據量
如果您使用的是.NET> = 4.0,請跳至我的答案以獲取更簡單的方法。 – Joshcodes 2013-06-04 18:45:22