我正在尝试在POST HTTP请求中同时设置请求正文数据和FileStream。但是仅文件被添加到请求正文中, POST BODY PARAMETERS 未添加
string fileUrl=@"E:\code.txt";
string url = "http://ptsv2.com/t/PostReq/post";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string boundaryString = "------------"+DateTime.Now.Ticks.ToString("x");
// Set the http request header \\
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "multipart/form-data;boundary=" + boundaryString;
request.KeepAlive = true;
request.Credentials =CredentialCache.DefaultCredentials;
// Use a MemoryStream to form the post data request,
// so that we can get the content-length attribute.
MemoryStream postDataStream = new MemoryStream();
StreamWriter postDataWriter = new StreamWriter(postDataStream);
// Include the file in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Dis-data;"+ "name=\"{0}\";"+ "filename=\"{1}\""+"\r\nContent-Type: {2}\r\n\r\n",
"myFile",
Path.GetFileName(fileUrl),
Path.GetExtension(fileUrl));
postDataWriter.Flush();
// Read the file
FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read,FileShare.ReadWrite);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postDataStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
postDataWriter.Flush();
// Dump the post data from the memory stream to the request stream
using (Stream stream = request.GetRequestStream())
{
string data="username=hello&pwd=test123";
byte[] postData = Encoding.ASCII.GetBytes(data);
stream.write(postData,0,postData.Length);
postDataStream.WriteTo(stream);
}
postDataStream.Close();
WebResponse response = request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string replyFromServer = responseReader.ReadToEnd();
MessageBox.Show(replyFromServer);
每次运行解决方案时,只有文件上传到服务器,而不是发布请求正文。
有人可以帮我解决这个问题吗?