[C#]在WinForm下使用HttpWebRequest上傳文件並顯示進度

要實現WinForm下的文件上傳,個人覺得采用FTP方法太麻煩,還得配置FTP服務器,要通過防火牆也是一個麻煩。本來打算採用WebClient方法,但是採用這個方法實現後,進度條很短時間後就達到最大值,要等待一段時間才能傳送完畢,要是文件太大(我這裏測試約100M),會出現錯誤。後來才知道,原來WebClient是在加載完整個文件到內存後才真正開始上傳,怪不得會出現前面的問題了。不得已參考了很多文章,老外的一個文章對我啓發很大(http://blogs.msdn.com/johan/archive/2006/11/15/are-you-getting-outofmemoryexceptions-when-uploading-large-files.aspx),是採用HttpWebRequest方法實現的。廢話少說,開始進入正題。實現過程如下:

 

[c-sharp] view plain copy
 print?
  1. 在WinForm裏面調用下面的方法來上傳文件:  
  2.   
  3. // <summary>  
  4.         /// 將本地文件上傳到指定的服務器(HttpWebRequest方法)  
  5.         /// </summary>  
  6.         /// <param name="address">文件上傳到的服務器</param>  
  7.         /// <param name="fileNamePath">要上傳的本地文件(全路徑)</param>  
  8.         /// <param name="saveName">文件上傳後的名稱</param>  
  9.         /// <param name="progressBar">上傳進度條</param>  
  10.         /// <returns>成功返回1,失敗返回0</returns>  
  11.         private int Upload_Request(string address, string fileNamePath, string saveName, ProgressBar progressBar)  
  12.         {  
  13.             int returnValue = 0;  
  14.   
  15.             // 要上傳的文件  
  16.             FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);  
  17.             BinaryReader r = new BinaryReader(fs);  
  18.   
  19.             //時間戳  
  20.             string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");  
  21.             byte[] boundaryBytes = Encoding.ASCII.GetBytes("/r/n--" + strBoundary + "/r/n");  
  22.   
  23.             //請求頭部信息  
  24.             StringBuilder sb = new StringBuilder();  
  25.             sb.Append("--");  
  26.             sb.Append(strBoundary);  
  27.             sb.Append("/r/n");  
  28.             sb.Append("Content-Disposition: form-data; name=/"");  
  29.             sb.Append("file");  
  30.             sb.Append("/"; filename=/"");  
  31.             sb.Append(saveName);  
  32.             sb.Append("/"");  
  33.             sb.Append("/r/n");  
  34.             sb.Append("Content-Type: ");  
  35.             sb.Append("application/octet-stream");  
  36.             sb.Append("/r/n");  
  37.             sb.Append("/r/n");  
  38.             string strPostHeader = sb.ToString();  
  39.             byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);  
  40.   
  41.             // 根據uri創建HttpWebRequest對象  
  42.             HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));  
  43.             httpReq.Method = "POST";  
  44.   
  45.             //對發送的數據不使用緩存  
  46.             httpReq.AllowWriteStreamBuffering = false;  
  47.   
  48.             //設置獲得響應的超時時間(300秒)  
  49.             httpReq.Timeout = 300000;  
  50.             httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;  
  51.             long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;  
  52.             long fileLength = fs.Length;  
  53.             httpReq.ContentLength = length;  
  54.             try  
  55.             {  
  56.                 progressBar.Maximum = int.MaxValue;  
  57.                 progressBar.Minimum = 0;  
  58.                 progressBar.Value = 0;  
  59.   
  60.                 //每次上傳4k  
  61.                 int bufferLength = 4096;  
  62.                 byte[] buffer = new byte[bufferLength];  
  63.   
  64.                 //已上傳的字節數  
  65.                 long offset = 0;  
  66.   
  67.                 //開始上傳時間  
  68.                 DateTime startTime = DateTime.Now;  
  69.                 int size = r.Read(buffer, 0, bufferLength);  
  70.                 Stream postStream = httpReq.GetRequestStream();  
  71.   
  72.                 //發送請求頭部消息  
  73.                 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);  
  74.                 while (size > 0)  
  75.                 {  
  76.                     postStream.Write(buffer, 0, size);  
  77.                     offset += size;  
  78.                     progressBar.Value = (int)(offset * (int.MaxValue / length));  
  79.                     TimeSpan span = DateTime.Now - startTime;  
  80.                     double second = span.TotalSeconds;  
  81.                     lblTime.Text = "已用時:" + second.ToString("F2") + "秒";  
  82.                     if (second > 0.001)  
  83.                     {  
  84.                         lblSpeed.Text = " 平均速度:" + (offset / 1024 / second).ToString("0.00") + "KB/秒";  
  85.                     }  
  86.                     else  
  87.                     {  
  88.                         lblSpeed.Text = " 正在連接…";  
  89.                     }  
  90.                     lblState.Text = "已上傳:" + (offset * 100.0 / length).ToString("F2") + "%";  
  91.                     lblSize.Text = (offset / 1048576.0).ToString("F2") + "M/" + (fileLength / 1048576.0).ToString("F2") + "M";  
  92.                     Application.DoEvents();  
  93.                     size = r.Read(buffer, 0, bufferLength);  
  94.                 }  
  95.                 //添加尾部的時間戳  
  96.                 postStream.Write(boundaryBytes, 0, boundaryBytes.Length);  
  97.                 postStream.Close();  
  98.   
  99.                 //獲取服務器端的響應  
  100.                 WebResponse webRespon = httpReq.GetResponse();  
  101.                 Stream s = webRespon.GetResponseStream();  
  102.                 StreamReader sr = new StreamReader(s);  
  103.   
  104.                 //讀取服務器端返回的消息  
  105.                 String sReturnString = sr.ReadLine();  
  106.                 s.Close();  
  107.                 sr.Close();  
  108.                 if (sReturnString == "Success")  
  109.                 {  
  110.                     returnValue = 1;  
  111.                 }  
  112.                 else if (sReturnString == "Error")  
  113.                 {  
  114.                     returnValue = 0;  
  115.                 }  
  116.   
  117.             }  
  118.             catch  
  119.             {  
  120.                 returnValue = 0;  
  121.             }  
  122.             finally  
  123.             {  
  124.                 fs.Close();  
  125.                 r.Close();  
  126.             }  
  127.   
  128.             return returnValue;  
  129.         }  
  130.   
  131. 參數說明如下:  
  132.   
  133. address:接收文件的URL地址,如:http://localhost/UploadFile/Save.aspx  
  134.   
  135. fileNamePath:要上傳的本地文件,如:D:/test.rar  
  136.   
  137. saveName:文件上傳到服務器後的名稱,如:200901011234.rar  
  138.   
  139. progressBar:顯示文件上傳進度的進度條。  
  140.   
  141. 接收文件的WebForm添加一個Save.aspx頁面,Load方法如下:  
  142.   
  143. protected void Page_Load(object sender, EventArgs e)  
  144.         {  
  145.             if (Request.Files.Count > 0)  
  146.             {  
  147.                 try  
  148.                 {  
  149.                     HttpPostedFile file = Request.Files[0];  
  150.                     string filePath = this.MapPath("UploadDocument") + "//" + file.FileName;  
  151.                     file.SaveAs(filePath);  
  152.                     Response.Write("Success/r/n");  
  153.                 }  
  154.                 catch  
  155.                 {  
  156.                     Response.Write("Error/r/n");  
  157.                 }  
  158.             }  
  159.    
  160.   
  161. 同時需要配置WebConfig文件的httpRuntime 如下:  
  162.   
  163. <httpRuntime maxRequestLength="102400"  executionTimeout="300"/>  
  164.   
  165. 不能的話最大隻能上傳4M了。要是想上傳更大的文件,maxRequestLength,executionTimeout設置大些,同時WinForm下的代碼行  
  166.   
  167. //設置獲得響應的超時時間(300秒)  
  168.             httpReq.Timeout = 300000;  
  169.   
  170. 也要修改,另外別忘了看看IIS的連接超時是否設置爲足夠大。  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章