我正在尝试使用.NET/C#上传文件并向我的网站发送一些参数。阅读了一些教程,其中有些只涉及参数或文件,我尝试将它们结合起来,但不成功。这是我的尝试:
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异常,显示“Header section has more than 10240 bytes (maybe it is not properly terminated)”,Wireshark告诉我发送的请求是一个畸形的数据包,其中MIME多部分是畸形的。
这里可能有几个问题,请让我知道你能发现的所有问题。
更新:为了将MIME与C#/.NET分开,我在这里创建了一个线程:https://stackoverflow.com/questions/1880002/error-in-mime-packet-for-http-post 更新2:因此,后端确实存在内容长度的问题,表示可读取的字节数小于声明的内容长度。但是!如果我相应地减少req.ContentLength中的内容长度,则没有足够大的缓冲区来发送数据。有什么建议吗?
更新3:实际上,看起来头部的大小与其所包含的数据量相比过大。