时间:2021-07-01 10:21:17 帮助过:38人阅读
<form action="sql.aspx" method="post" enctype="multipart/form-data">
<input id="Text1" name="content" type="text" /><br />
<input id="Text2" name="uploadImg" type="text" /><br />
<input id="File1" type="file" name="image0" /><br />
<input id="Submit1" type="submit" value="submit" />
</form>
为了查看表单提交时,向服务端post了什么数据,这里我使用Fiddler来查看。Fiddler确实是个不错的工具,注意当url主机地址是localhost时Fiddler捕获不到,需要再localhost后加一点(.)即可,打开Fiddler,浏览带上面form的page,输入数据提交,此时在Fiddler中可看到post的数据了。下面是一部份数据的截图。
分析其中的数据不难得出,一个表单中的数据域(input type="text")对应的格式为
-----------------------------7da119c1004a6
Content-Disposition: form-data; name="content"
this is a txt value
一个文件(input type="file")对应的格式为(通常为表单最后一个参数)
-----------------------------7da119c1004a6
Content-Disposition: form-data; name="image0"; filename="E:\CAI\875.jpg"
Content-Type: image/pjpeg
[文件内容]
结尾处是-----------------------------7da119c1004a6--
有了上面的数据做参考,按照其格式组织数据,post到服务端,同样可以达到html form提交的效果。要特别注意其格式:如回车换行,差一个都可能得不到正确的响应,还有请求的Content-Length一定计算对。下面是一个参考:
代码
代码如下:
public string POSTfile(string v1,string v2, string file)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//请求
WebRequest req = WebRequest.Create(@"http://localhost.:4944/WebSite1/getfile.aspx");
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
//组织表单数据
StringBuilder sb = new StringBuilder();
sb.Append("--" + boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"content\"");
sb.Append("\r\n\r\n");
sb.Append(v1);
sb.Append("\r\n");
sb.Append("--" + boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"uploadImg\"");
sb.Append("\r\n\r\n");
sb.Append("v2");
sb.Append("\r\n");
sb.Append("--" + boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"image0\"; filename=\"e:\\a.jpg\"");
sb.Append("\r\n");
sb.Append("Content-Type: image/pjpeg");
sb.Append("\r\n\r\n");
string head = sb.ToString();
byte[] form_data = Encoding.UTF8.GetBytes(head);
//结尾
byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
//文件
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
//post总长度
long length = form_data.Length + fileStream.Length + foot_data.Length;
req.ContentLength = length;
Stream requestStream = req.GetRequestStream();
//发送表单参数
requestStream.Write(form_data, 0, form_data.Length);
//文件内容
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
//结尾
requestStream.Write(foot_data, 0, foot_data.Length);
requestStream.Close();
//响应
WebResponse pos = req.GetResponse();
StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8);
string html = sr.ReadToEnd().Trim();
sr.Close();
if (pos != null)
{
pos.Close();
pos = null;
}
if (req != null)
{
req = null;
}
return html;
}