static void FileUpload(string m_fileNamePath, string wenjianmin)
{
string Boundary = "wojuedezhgexiangmushigekeng";
//构造请求参数
Dictionary<string, string> PostInfo = new Dictionary<string, string>();
//PostInfo.Add("sequenceNo ", "A0002");
//PostInfo.Add("type", "application/vnd.ms-excel");
//PostInfo.Add("file", "");
//PostInfo.Add("filename", wenjianmin);
//构造POST请求体
StringBuilder PostContent = new StringBuilder("--" + Boundary);
byte[] ContentEnd = Encoding.UTF8.GetBytes("--" + Boundary + "--\r\n");//请求体末尾,后面会用到
//组成普通参数信息
foreach (KeyValuePair<string, string> item in PostInfo)
{
PostContent.Append("\r\n")
.Append("Content-Disposition: form-data; name=\"")
.Append(item.Key + "\"").Append("\r\n")
.Append("\r\n").Append(item.Value).Append("\r\n")
.Append("--").Append(Boundary);
}
//转换为二进制数组,后面会用到
byte[] PostContentByte = Encoding.UTF8.GetBytes(PostContent.ToString());
//文件信息
byte[] UpdateFile = File2Bytes(m_fileNamePath);//转换为二进制
StringBuilder FileContent = new StringBuilder();
FileContent.Append("\r\n")
.Append("Content-Disposition:form-data; name=\"")
.Append("flie" + "\"; ")
.Append("filename=\"")
.Append(wenjianmin + "\"")
.Append("\r\n")
.Append("Content-Type: application/vnd.ms-excel")
.Append("\r\n")
.Append("\r\n");
byte[] FileContentByte = Encoding.UTF8.GetBytes(FileContent.ToString());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_address);
request.Method = "POST";
request.Timeout = 100000;
//这里确定了分隔符是什么
request.Headers.Add("Cookie", "JSESSIONID=19FCE6CF428E78732830248719E3836A");
//request.Headers.Add("Accept-Encoding", " gzip, deflate");
request.ContentType = "multipart/form-data;boundary=" + Boundary;
//request.Cookie = "";
//定义请求流
Stream myRequestStream = request.GetRequestStream();
myRequestStream.Write(PostContentByte, 0, PostContentByte.Length);//写入参数
myRequestStream.Write(FileContentByte, 0, FileContentByte.Length);//写入文件信息
myRequestStream.Write(UpdateFile, 0, UpdateFile.Length);//文件写入请求流中
myRequestStream.Write(ContentEnd, 0, ContentEnd.Length);//写入结尾
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
//StreamReader sr = new StreamReader(res.GetResponseStream(), strEncode);
//strHtml = sr.ReadToEnd();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取返回值
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myRequestStream.Close();
myStreamReader.Close();
myResponseStream.Close();
}
以下是抓包截图

返回错误信息
{"timestamp":"2020-01-09 13:40:35","status":500,"error":"Internal Server Error","message":"Failed to parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly","path":"/lab/calibrator/uploadReport"}