说明:1.WebRequest类是一个抽象类,所以上传类实际使用的是其子类
2.打开Fiddler软件,监视正常网页的文件上传,可以看到http协议的请求和响应信息,简略说明
(第一行:请求说明
POST http://localhost/UpLoad.aspx HTTP/1.1 (请求类型:post,请求地址: http://localhost/UpLoad.aspx,http协议类型:HTTP/1.1)
第二行至多行:请求头(一系列的 key:value)
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type: multipart/form-data;charset=utf-8;boundary=8D30475B6E5BB4C
Host:localhost
Content-Length: 22194
Expect: 100-continue
Connection: Close
换行,第n行:请求体
响应类似,详细见fiddler。
3.通过查看fiddler监测的http请求过程,可以利用webrequest模拟http请求,代码如下:
private void UploadFile(string path)
{
try
{
if (!string.IsNullOrEmpty(path))
{
string filename = Path.GetFileName(path); //获取文件名称
LogWrite("上传文件", "开始上传文件,文件名称" + filename, null);
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/UpLoad.aspx");
request.ServicePoint.ConnectionLimit = ; //设置最大连接数
request.ServicePoint.Expect100Continue = false;//解决webexception操作超时
request.Method = "POST"; //请求方法
#region ==请求头===
request.KeepAlive = false; //请求连接方式,设置为请求完成后断开连接
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
#endregion
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");//分割线数据
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");//结束分割线数据
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", filename));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); //上传文件头数据
string sbheader2 = string.Format("Content-Disposition:form-data;name=\"ws\"\r\n\r\nother");//其他的form表单数据,这里为:form["ws"]="other"
byte[] ddd = Encoding.UTF8.GetBytes(sbheader2);
FileStream fs = new FileStream(path, FileMode.Open);//读取文件
byte[] bArr = new byte[fs.Length];
long filesize = fs.Length;
fs.Read(bArr, , (int)filesize);
fs.Close();
request.ContentLength = itemBoundaryBytes.Length * + ddd.Length + postHeaderBytes.Length + filesize + endBoundaryBytes.Length;//设置请求长度,一定要设置,否则可能会引发请求超时的异常
Stream sm = request.GetRequestStream(); //获取请求流
sm.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);//写入分割线数据
sm.Write(ddd, , ddd.Length); //写入表单数据
sm.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);//写入分割线数据
sm.Write(postHeaderBytes, , postHeaderBytes.Length);//写入上传文件头数据 long size = ;
float percent = ; //上传进度
//分步上传
while (size < filesize)
{
if (filesize - size > )
{
sm.Write(bArr, (int)size, );
size += ;
}
else
{
sm.Write(bArr, (int)size, (int)(filesize - size));
size = filesize;
}
percent = size / (float)filesize;
}
//sm.Write(bArr, 0, bArr.Length); sm.Write(endBoundaryBytes, , endBoundaryBytes.Length); //写入结束分割线
sm.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取响应
Stream sss = response.GetResponseStream();
LogWrite("上传文件", response.StatusCode.ToString() + filename, null); //Stream sss = request.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(sss);
string ret = sr.ReadToEnd();
sr.Close();
LogWrite("上传文件", "结束上传文件,返回结果" + ret, null);
//资源释放
response.Close();
request.Abort();
System.GC.Collect();
}
}
catch (Exception ex)
{
LogWrite("上传文件发生异常", "", ex);
} }
4.注意:一定要设置request.ContentLength的大小,否则可能引发操作超时的异常信息。