分享

[C#]在WinForm下使用HttpWebRequest上传文件并显示进度

 caoyc1989 2014-04-19
  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的连接超时是否设置为足够大。  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多