复制代码 代码如下:
<form action="sql.aspx" method="post" enctype="multipart/form-data">
<input type="text" /><br />
<input type="text" /><br />
<input type="file" /><br />
<input type="submit" value="submit" />
</form>
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;
}
新闻热点
疑难解答
图片精选