c# 文件上传
1.客户端文件上传功能:
1 /// <summary> 2 /// Http上传文件 3 /// </summary> 4 public static string HttpUploadFile(string url, string path) 5 { 6 // 设置参数 7 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 8 CookieContainer cookieContainer = new CookieContainer(); 9 request.CookieContainer = cookieContainer; 10 request.AllowAutoRedirect = true; 11 request.Method = "POST"; 12 string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 13 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; 14 byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); 15 byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); 16 17 int pos = path.LastIndexOf("\\"); 18 string fileName = path.Substring(pos + 1); 19 20 //请求头部信息 21 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)); 22 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); 23 24 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); 25 byte[] bArr = new byte[fs.Length]; 26 fs.Read(bArr, 0, bArr.Length); 27 fs.Close(); 28 29 Stream postStream = request.GetRequestStream(); 30 postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); 31 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 32 postStream.Write(bArr, 0, bArr.Length); 33 postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); 34 postStream.Close(); 35 36 //发送请求并获取相应回应数据 37 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 38 //直到request.GetResponse()程序才开始向目标网页发送Post请求 39 Stream instream = response.GetResponseStream(); 40 StreamReader sr = new StreamReader(instream, Encoding.UTF8); 41 //返回结果网页(html)代码 42 string content = sr.ReadToEnd(); 43 return content; 44 }
web服务器使用handler存储客户端上传的文件:
1 public void ProcessRequest(HttpContext context) 2 { 3 context.Response.ContentType = "text/plain"; 4 //context.Response.Write("Hello World"); 5 6 Random r = new Random(); 7 8 string filePath = "test" + r.Next(0, 999999999) + ".jpg"; 9 string url = context.Server.MapPath("~/Resource/Icon/" + filePath); 10 foreach (string v in context.Request.Files.AllKeys) 11 { 12 HttpPostedFile file = context.Request.Files[v]; 13 14 file.SaveAs(url); 15 } 16 context.Response.Write("Succeed"); 17 18 }
3.客户端同步/异步下载
下载帮助类
/// <summary> /// 下载请求信息 /// </summary> public class DownloadTmp { /// <summary> /// 文件名 /// </summary> public string fileName; /// <summary> /// 下载路径 /// </summary> public string filePath; /// <summary> /// 下载进度回调 /// </summary> public Action<int> loadingCallback; /// <summary> /// 完成回调 /// </summary> public Action succeedCallback; /// <summary> /// 失败回调 /// </summary> public Action failedCallback; /// <summary> /// webRequest /// </summary> public HttpWebRequest webRequest; }
下载工具类:
/// <summary> /// 下载工具类 /// </summary> public class HttpDownloadTool { /// <summary> /// 异步回调 /// </summary> /// <param name="result">Result.</param> private static void BeginResponseCallback(IAsyncResult result) { DownloadTmp downloadInfo = (DownloadTmp)result.AsyncState; HttpWebRequest Request = downloadInfo.webRequest; HttpWebResponse Response = (HttpWebResponse)Request.EndGetResponse(result); if (Response.StatusCode == HttpStatusCode.OK) { string filePath = downloadInfo.filePath; if (File.Exists(filePath)) { File.Delete(filePath); } FileStream fs = File.OpenWrite(filePath); Stream stream = Response.GetResponseStream(); int count = 0; int num = 0; if (Response.ContentLength == 0) { Debug.Log("Error:-----------Response.ContantLength === 0"); } else { Debug.Log("FileLength:-----------Resoponse.ContantLength === " + Response.ContentLength); var buffer = new byte[2048 * 100]; do { num++; count = stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, count); Debug.Log("buffer count = " + fs.Length.ToString()); if (downloadInfo.loadingCallback != null) { float pro = (float)fs.Length / Response.ContentLength * 100; downloadInfo.loadingCallback((int)pro); } } while (count > 0); } fs.Close(); Response.Close(); if (downloadInfo.succeedCallback != null) { Debug.Log("succeedCallback-==============succeedCallback"); downloadInfo.succeedCallback(); } } else { Debug.Log("Error == " + Response.StatusCode.ToString()); Response.Close(); if (downloadInfo.failedCallback != null) { Debug.Log("downloading-==============failedCallback"); downloadInfo.failedCallback(); } } } /// <summary> /// 下载文件,异步 /// </summary> /// <param name="URL">下载路径</param> /// <param name="downloadPath">文件下载路径</param> /// <returns></returns> public static void HttpDownloadZip(string URL, ref DownloadTmp downloadInfo) { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL); downloadInfo.webRequest = Request; Request.BeginGetResponse(BeginResponseCallback, downloadInfo); } /// <summary> /// 下载文件同步 /// </summary> /// <param name="URL">下载路径</param> /// <param name="downloadPath">文件下载路径</param> /// <returns></returns> public static bool HttpDownloadFile(string URL, string fileName, string filePath, Action<int> callback = null) { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL); HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); if (Response.StatusCode == HttpStatusCode.OK) { if (File.Exists(filePath)) { File.Delete(filePath); } FileStream fs = File.OpenWrite(filePath); Stream stream = Response.GetResponseStream(); int count = 0; int num = 0; if (Response.ContentLength == 0) { Debug.Log("Error:-----------Response.ContantLength === 0"); } else { Debug.Log("FileLength:-----------Resoponse.ContantLength === " + Response.ContentLength); var buffer = new byte[2048 * 100]; do { num++; count = stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, count); Debug.Log("buffer count = " + fs.Length.ToString()); if (callback != null) { float pro = (float)fs.Length / Response.ContentLength * 100; callback((int)pro); } } while (count > 0); } fs.Close(); Response.Close(); } else { Debug.Log("Error == " + Response.StatusCode.ToString()); Response.Close(); return false; } return true; } }
嗯,努力!