C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法
本文实例讲述了C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法,在项目开发中有一定的实用价值,具体方法如下:
一、前言:
这篇文章翻译来自madmik3写在CodeProject上的文章,原标题为:C#'sWebClient.UploadFilewithmorefunctionality.
二、正文:
我们使用WebRequest来获取网页内容是非常简单的,可是用他来上传文件就没有那么简单了。
如果我们在网页中上传文件,加入下面代码即可:
HTML文件上传代码实例:
<formaction="http://localhost/test.php"method=POST> <inputtype=textname=uname> <inputtype=passwordname=passwd> <inputtype=FILEname=uploadfile> <inputtype=submit> </form>
但,如果在C#中使用WebRequest上传,必须对本地文件进行相应的处理才能提交到指定的HTTP地址,下面这个函数哦就帮我们做了这烦恼的操作
UploadFileEx上传文件函数:
publicstaticstringUploadFileEx(stringuploadfile,stringurl,
stringfileFormName,stringcontenttype,NameValueCollectionquerystring,
CookieContainercookies)
{
if((fileFormName==null)||
(fileFormName.Length==0))
{
fileFormName="file";
}
if((contenttype==null)||
(contenttype.Length==0))
{
contenttype="application/octet-stream";
}
stringpostdata;
postdata="?";
if(querystring!=null)
{
foreach(stringkeyinquerystring.Keys)
{
postdata+=key+"="+querystring.Get(key)+"&";
}
}
Uriuri=newUri(url+postdata);
stringboundary="----------"+DateTime.Now.Ticks.ToString("x");
HttpWebRequestwebrequest=(HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer=cookies;
webrequest.ContentType="multipart/form-data;boundary="+boundary;
webrequest.Method="POST";
//Buildupthepostmessageheader
StringBuildersb=newStringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("");
sb.Append("Content-Disposition:form-data;name=\"");
sb.Append(fileFormName);
sb.Append("\";filename=\"");
sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("");
sb.Append("Content-Type:");
sb.Append(contenttype);
sb.Append("");
sb.Append("");
stringpostHeader=sb.ToString();
byte[]postHeaderBytes=Encoding.UTF8.GetBytes(postHeader);
//Buildthetrailingboundarystringasabytearray
//ensuringtheboundaryappearsonalinebyitself
byte[]boundaryBytes=
Encoding.ASCII.GetBytes("--"+boundary+"");
FileStreamfileStream=newFileStream(uploadfile,
FileMode.Open,FileAccess.Read);
longlength=postHeaderBytes.Length+fileStream.Length+
boundaryBytes.Length;
webrequest.ContentLength=length;
StreamrequestStream=webrequest.GetRequestStream();
//Writeoutourpostheader
requestStream.Write(postHeaderBytes,0,postHeaderBytes.Length);
//Writeoutthefilecontents
byte[]buffer=newByte[checked((uint)Math.Min(4096,
(int)fileStream.Length))];
intbytesRead=0;
while((bytesRead=fileStream.Read(buffer,0,buffer.Length))!=0)
requestStream.Write(buffer,0,bytesRead);
//Writeoutthetrailingboundary
requestStream.Write(boundaryBytes,0,boundaryBytes.Length);
WebResponseresponce=webrequest.GetResponse();
Streams=responce.GetResponseStream();
StreamReadersr=newStreamReader(s);
returnsr.ReadToEnd();
}
调用代码如下:
CookieContainercookies=newCookieContainer(); //addorusecookies NameValueCollectionquerystring=newNameValueCollection(); querystring["uname"]="uname"; querystring["passwd"]="snake3"; stringuploadfile;//settofiletoupload uploadfile="c:\\test.jpg"; //everythingexceptuploadfileandurlcanbeleftblankifneeded stringoutdata=UploadFileEx(uploadfile, "http://localhost/test.php","uploadfile","image/pjpeg", querystring,cookies);
至此,所有主要功能代码都已经介绍完毕,至于美化你的程序就要读者根据自己的喜好完成了。
作者还提供了接收文件的PHP代码,,个人觉得既然能写上传的程序,接收文件的ServerPage应该不在话下的,况且又不是PHP才能接收提交的文件,ASP,ASP.NET,JSP都可以,这里就不再啰嗦了。