转载自:http://www.codeproject.com/KB/cs/uploadfileex.aspx
前言:
这篇文章翻译来自madmik3 写在 CodeProject 上的文章,原标题为: C#'s WebClient.UploadFile with more functionality.
正文:
我们使用 WebRequest 来获取网页内容是非常简单的,可是用他来上传文件就没有那么简单了。
如果我们在网页中上传文件,加入下面代码即可:
HTML 文件上传代码实例
- <form action ="http://localhost/test.php" method = POST>
- <input type = text name = uname>
- <input type = password name =passwd>
- <input type = FILE name = uploadfile>
- <input type=submit>
- </form>
但,如果在C#中使用 WebRequest 上传,必须对本地文件进行相应的处理才能提交到指定的HTTP地址,下面这个函数哦就帮我们做了这烦恼的操作
UploadFileEx 上传文件函数
- public static string UploadFileEx( string uploadfile, string url,
- string fileFormName, string contenttype,NameValueCollection querystring,
- CookieContainer cookies)
- {
- if( (fileFormName== null) ||
- (fileFormName.Length ==0))
- {
- fileFormName = "file";
- }
- if( (contenttype== null) ||
- (contenttype.Length ==0))
- {
- contenttype = "application/octet-stream";
- }
- string postdata;
- postdata = "?";
- if (querystring!=null)
- {
- foreach(string key in querystring.Keys)
- {
- postdata+= key +"=" + querystring.Get(key)+"&";
- }
- }
- Uri uri = new Uri(url+postdata);
- string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
- HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
- webrequest.CookieContainer = cookies;
- webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
- webrequest.Method = "POST";
- // Build up the post message header
- StringBuilder sb = new StringBuilder();
- 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("");
- string postHeader = sb.ToString();
- byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
- // Build the trailing boundary string as a byte array
- // ensuring the boundary appears on a line by itself
- byte[] boundaryBytes =
- Encoding.ASCII.GetBytes("--" + boundary + "");
- FileStream fileStream = new FileStream(uploadfile,
- FileMode.Open, FileAccess.Read);
- long length = postHeaderBytes.Length + fileStream.Length +
- boundaryBytes.Length;
- webrequest.ContentLength = length;
- Stream requestStream = webrequest.GetRequestStream();
- // Write out our post header
- requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
- // Write out the file contents
- 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);
- // Write out the trailing boundary
- requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
- WebResponse responce = webrequest.GetResponse();
- Stream s = responce.GetResponseStream();
- StreamReader sr = new StreamReader(s);
- return sr.ReadToEnd();
- }
调用代码如下:
调用代码
- CookieContainer cookies = new CookieContainer();
- //add or use cookies
- NameValueCollection querystring = new NameValueCollection();
- querystring["uname"]="uname";
- querystring["passwd"]="snake3";
- string uploadfile;// set to file to upload
- uploadfile = "c:\\test.jpg";
- //everything except upload file and url can be left blank if needed
- string outdata = UploadFileEx(uploadfile,
- "http://localhost/test.php","uploadfile", "image/pjpeg",
- querystring,cookies);
至此,所有代码都已经奉献完毕,接下来就看你怎么去美化你的程序了。
作者还提供了接收文件的PHP代码,,我觉得既然能写上传的程序,接收文件的Server Page应该不在话下的,况且又不是PHP才能接收提交的文件,ASP,ASP.NET,JSP都可以,所以就不贴了。