1、关于WebClient第三方的封装,支持多文件上传等
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Collections; using System.IO; using System.Text.RegularExpressions; using RE = System.Text.RegularExpressions.Regex; using System.Security.Cryptography.X509Certificates; /*************************************************************************************************************************************************** * *文件名:HttpProc.cs * *创建人:kenter * *日 期:2010.02.23 修改 * *描 述:实现HTTP协议中的GET、POST请求 * *使 用:HttpProc.WebClient client = new HttpProc.WebClient(); client.Encoding = System.Text.Encoding.Default;//默认编码方式,根据需要设置其他类型 client.OpenRead("http://www.baidu.com");//普通get请求 MessageBox.Show(client.RespHtml);//获取返回的网页源代码 client.DownloadFile("http://www.codepub.com/upload/163album.rar",@"C:\163album.rar");//下载文件 client.OpenRead("http://passport.baidu.com/?login","username=zhangsan&password=123456");//提交表单,此处是登录百度的示例 client.UploadFile("http://hiup.baidu.com/zhangsan/upload", @"file1=D:\1.mp3");//上传文件 client.UploadFile("http://hiup.baidu.com/zhangsan/upload", "folder=myfolder&size=4003550",@"file1=D:\1.mp3");//提交含文本域和文件域的表单 *****************************************************************************************************************************************************/namespace HttpProc{ //////上传事件委托 /// /// /// public delegate void WebClientUploadEvent(object sender, HttpProc.UploadEventArgs e); //////下载事件委托 /// /// /// public delegate void WebClientDownloadEvent(object sender, HttpProc.DownloadEventArgs e); //////上传事件参数 /// public struct UploadEventArgs { //////上传数据总大小 /// public long totalBytes; //////已发数据大小 /// public long bytesSent; //////发送进度(0-1) /// public double sendProgress; //////发送速度Bytes/s /// public double sendSpeed; } //////下载事件参数 /// public struct DownloadEventArgs { //////下载数据总大小 /// public long totalBytes; //////已接收数据大小 /// public long bytesReceived; //////接收数据进度(0-1) /// public double ReceiveProgress; //////当前缓冲区数据 /// public byte[] receivedBuffer; //////接收速度Bytes/s /// public double receiveSpeed; } //////实现向WEB服务器发送和接收数据 /// public class WebClient { private WebHeaderCollection requestHeaders, responseHeaders; private TcpClient clientSocket; private MemoryStream postStream; private Encoding encoding = Encoding.Default; private const string BOUNDARY = "--HEDAODE--"; private const int SEND_BUFFER_SIZE = 10245; private const int RECEIVE_BUFFER_SIZE = 10245; private string cookie = ""; private string respHtml = ""; private string strRequestHeaders = ""; private string strResponseHeaders = ""; private int statusCode = 0; private bool isCanceled = false; public event WebClientUploadEvent UploadProgressChanged; public event WebClientDownloadEvent DownloadProgressChanged; //////初始化WebClient类 /// public WebClient() { responseHeaders = new WebHeaderCollection(); requestHeaders = new WebHeaderCollection(); } ////// 获得字符串中开始和结束字符串中间得值 /// /// /// 开始 /// 结束 ///public string gethtmlContent(string str, string s, string e) { Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline); return rg.Match(str).Value; } /// /// 过滤HTML字符 /// /// ///public string htmlConvert(string source) { string result; //remove line breaks,tabs result = source.Replace("\r", " "); result = result.Replace("\n", " "); result = result.Replace("\t", " "); //remove the header result = Regex.Replace(result, "().*()", string.Empty, RegexOptions.IgnoreCase); result = Regex.Replace(result, @"<( )*script([^>])*>", ")", string.Empty, RegexOptions.IgnoreCase); //remove all styles result = Regex.Replace(result, @"<( )*style([^>])*>", ")", string.Empty, RegexOptions.IgnoreCase); //insert tabs in spaces of tags result = Regex.Replace(result, @"<( )*td([^>])*>", " ", RegexOptions.IgnoreCase); //insert line breaks in places of and
tags result = Regex.Replace(result, @"<( )*tr([^>])*>", "\r\r", RegexOptions.IgnoreCase); result = Regex.Replace(result, @"<( )*p([^>])*>", "\r\r", RegexOptions.IgnoreCase); //remove anything thats enclosed inside < > result = Regex.Replace(result, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase); //replace special characters: result = Regex.Replace(result, @"&", "&", RegexOptions.IgnoreCase); result = Regex.Replace(result, @" ", " ", RegexOptions.IgnoreCase); result = Regex.Replace(result, @"<", "<", RegexOptions.IgnoreCase); result = Regex.Replace(result, @">", ">", RegexOptions.IgnoreCase); result = Regex.Replace(result, @"&(.{2,6});", string.Empty, RegexOptions.IgnoreCase); //remove extra line breaks and tabs result = Regex.Replace(result, @" ( )+", " "); result = Regex.Replace(result, "(\r)( )+(\r)", "\r\r"); result = Regex.Replace(result, @"(\r\r)+", "\r\n"); return result; } ///
2、WebRequest实现多文件文件上载
封装类:public class UploadFile { public UploadFile() { ContentType = "application/octet-stream"; } public string Name { get; set; } public string Filename { get; set; } public string ContentType { get; set; } public Stream Stream { get; set; } } class ClassTest { public byte[] UploadFiles(string address, IEnumerablefiles, NameValueCollection values) { var request = WebRequest.Create(address); request.Method = "POST"; var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo); request.ContentType = "multipart/form-data; boundary=" + boundary; boundary = "--" + boundary; using (var requestStream = request.GetRequestStream()) { // Write the values foreach (string name in values.Keys) { var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine); requestStream.Write(buffer, 0, buffer.Length); buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}", name, Environment.NewLine)); requestStream.Write(buffer, 0, buffer.Length); buffer = Encoding.UTF8.GetBytes(values[name] + Environment.NewLine); requestStream.Write(buffer, 0, buffer.Length); } // Write the files foreach (var file in files) { var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine); requestStream.Write(buffer, 0, buffer.Length); buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", file.Name, file.Filename, Environment.NewLine)); requestStream.Write(buffer, 0, buffer.Length); buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", file.ContentType, Environment.NewLine)); requestStream.Write(buffer, 0, buffer.Length); file.Stream.CopyTo(requestStream); buffer = Encoding.ASCII.GetBytes(Environment.NewLine); requestStream.Write(buffer, 0, buffer.Length); } var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--"); requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length); } using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) using (var stream = new MemoryStream()) { responseStream.CopyTo(stream); return stream.ToArray(); } } }
使用:
using (var stream1 = File.Open("test.txt", FileMode.Open)) using (var stream2 = File.Open("test.xml", FileMode.Open)) using (var stream3 = File.Open("test.pdf", FileMode.Open)) { var files = new[] { new UploadFile { Name = "file", Filename = "test.txt", ContentType = "text/plain", Stream = stream1 }, new UploadFile { Name = "file", Filename = "test.xml", ContentType = "text/xml", Stream = stream2 }, new UploadFile { Name = "file", Filename = "test.pdf", ContentType = "application/pdf", Stream = stream3 } }; var values = new NameValueCollection { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" }, }; byte[] result = UploadFiles("http://localhost:1234/upload", files, values); }
3、下面HttpWebRequestt
C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法
我们使用 WebRequest 来获取网页内容是非常简单的,可是用他来上传文件就没有那么简单了。
如果我们在网页中上传文件,加入下面代码即可:
HTML 文件上传代码实例:
但,如果在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);