c# - 带有文件和参数的 WebRequest POST

标签 c# .net http post httpwebrequest

我正在尝试使用 .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 bnytes (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:实际上,与它包含的数据量相比,标题看起来太大了

最佳答案

问题是您缺少“\n”。下面一行:

string postData = "--" + boundary + "\nContent-Disposition: form-data\n";

应该是:

string postData = "--" + boundary + "\nContent-Disposition: form-data\n\n";

还有这一行:

postData += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"file\" filename=\"upload.pdf\" Content-Type: application/pdf\n\n"

在“Content-Type”之前缺少“\n”。应该是:

postData += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"file\" filename=\"upload.pdf\"\nContent-Type: application/pdf\n\n"

关于c# - 带有文件和参数的 WebRequest POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1874410/

相关文章:

c# - 在 C# 中运行 Java 代码

c# - 这个 AppendFormat 有什么值(value)吗?

没有 MessageBox,C# DLL 无法工作

c# - 使用 OR 运算符在 LINQ 表达式中添加 Between 子句

c# - 您能否编译 C#,使其在运行时不需要 .NET Framework?

c# - 在 2D 中查找远程点

c# - Unity 从对象 c 接收事件

javascript - 快速迭代时处理缓存js文件的最佳方式

java - Java 的灵活低级 http 库?

http - 服务器启动后如何更改 http.Handle() 中的处理程序?