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
在WinForm裡面呼叫下面的方法來上傳檔案:
- // <summary>
- /// 將本地檔案上傳到指定的伺服器(HttpWebRequest方法)
- /// </summary>
- /// <param name="address">檔案上傳到的伺服器</param>
- /// <param name="fileNamePath">要上傳的本地檔案(全路徑)</param>
- /// <param name="saveName">檔案上傳後的名稱</param>
- /// <param name="progressBar">上傳進度條</param>
- /// <returns>成功返回1,失敗返回0</returns>
- privateint Upload_Request(string address, string fileNamePath, string saveName, ProgressBar progressBar)
- {
- int returnValue = 0;
- // 要上傳的檔案
- FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
- BinaryReader r = new BinaryReader(fs);
- //時間戳
- string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
- byte[] boundaryBytes = Encoding.ASCII.GetBytes("/r/n--" + strBoundary + "/r/n");
- //請求頭部資訊
- StringBuilder sb = new StringBuilder();
- sb.Append("--");
- sb.Append(strBoundary);
- sb.Append("/r/n");
- sb.Append("Content-Disposition: form-data; name=/"");
- sb.Append("file");
- sb.Append("/"; filename=/"");
- sb.Append(saveName);
- sb.Append("/"");
- sb.Append("/r/n");
- sb.Append("Content-Type: ");
- sb.Append("application/octet-stream");
- sb.Append("/r/n");
- sb.Append("/r/n");
- string strPostHeader = sb.ToString();
- byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
- // 根據uri建立HttpWebRequest物件
- HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
- httpReq.Method = "POST";
- //對傳送的資料不使用快取
- httpReq.AllowWriteStreamBuffering = false;
- //設定獲得響應的超時時間(300秒)
- httpReq.Timeout = 300000;
- httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
- long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
- long fileLength = fs.Length;
- httpReq.ContentLength = length;
- try
- {
- progressBar.Maximum = int.MaxValue;
- progressBar.Minimum = 0;
- progressBar.Value = 0;
- //每次上傳4k
- int bufferLength = 4096;
- byte[] buffer = newbyte[bufferLength];
- //已上傳的位元組數
- long offset = 0;
- //開始上傳時間
- DateTime startTime = DateTime.Now;
- int size = r.Read(buffer, 0, bufferLength);
- Stream postStream = httpReq.GetRequestStream();
- //傳送請求頭部訊息
- postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
- while (size > 0)
- {
- postStream.Write(buffer, 0, size);
- offset += size;
- progressBar.Value = (int)(offset * (int.MaxValue / length));
- TimeSpan span = DateTime.Now - startTime;
- double second = span.TotalSeconds;
- lblTime.Text = "已用時:" + second.ToString("F2") + "秒";
- if (second > 0.001)
- {
- lblSpeed.Text = " 平均速度:" + (offset / 1024 / second).ToString("0.00") + "KB/秒";
- }
- else
- {
- lblSpeed.Text = " 正在連線…";
- }
- lblState.Text = "已上傳:" + (offset * 100.0 / length).ToString("F2") + "%";
- lblSize.Text = (offset / 1048576.0).ToString("F2") + "M/" + (fileLength / 1048576.0).ToString("F2") + "M";
- Application.DoEvents();
- size = r.Read(buffer, 0, bufferLength);
- }
- //新增尾部的時間戳
- postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
- postStream.Close();
- //獲取伺服器端的響應
- WebResponse webRespon = httpReq.GetResponse();
- Stream s = webRespon.GetResponseStream();
- StreamReader sr = new StreamReader(s);
- //讀取伺服器端返回的訊息
- String sReturnString = sr.ReadLine();
- s.Close();
- sr.Close();
- if (sReturnString == "Success")
- {
- returnValue = 1;
- }
- elseif (sReturnString == "Error")
- {
- returnValue = 0;
- }
- }
- catch
- {
- returnValue = 0;
- }
- finally
- {
- fs.Close();
- r.Close();
- }
- return returnValue;
- }
引數說明如下:
fileNamePath:要上傳的本地檔案,如:D:/test.rar
saveName:檔案上傳到伺服器後的名稱,如:200901011234.rar
progressBar:顯示檔案上傳進度的進度條。
接收檔案的WebForm新增一個Save.aspx頁面,Load方法如下:
- protectedvoid Page_Load(object sender, EventArgs e)
- {
- if (Request.Files.Count > 0)
- {
- try
- {
- HttpPostedFile file = Request.Files[0];
- string filePath = this.MapPath("UploadDocument") + "//" + file.FileName;
- file.SaveAs(filePath);
- Response.Write("Success/r/n");
- }
- catch
- {
- Response.Write("Error/r/n");
- }
- }
同時需要配置WebConfig檔案的httpRuntime 如下:
<httpRuntime maxRequestLength="102400" executionTimeout="300"/>
不能的話最大隻能上傳4M了。要是想上傳更大的檔案,maxRequestLength,executionTimeout設定大些,同時WinForm下的程式碼行
//設定獲得響應的超時時間(300秒)
httpReq.Timeout = 300000;
也要修改,另外別忘了看看IIS的連線超時是否設定為足夠大。
一切都配置好了,執行效果如下:
為了解決這個問題,我查看了很多文章,記於此,以後遇到同樣的問題有個查詢的地方。