将本地文件上传到指定的服务器(HttpWebRequest方法)

时间:2024-02-18 11:21:30

将本地文件上传到指定的服务器(HttpWebRequest方法),通过文件流,带文件名,同文件一同上传的表单文本域及值.

  1      ///<summary>
  2         /// 将本地文件上传到指定的服务器(HttpWebRequest方法)
  3         /// </summary>
  4         /// <param name="address">文件上传到的服务器</param>
  5         /// <param name="fileNamePath">要上传的本地文件(全路径)</param>
  6         /// <param name="saveName">文件上传后的名称</param>
  7         /// <param name="progressBar">上传进度条</param>
  8         /// <returns>成功返回1,失败返回0</returns>
  9         private string UploadRequest(string url, string filePath, string fileName)
 10         {
 11             string returnValue = "";
 12             // 要上传的文件
 13             FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
 14             BinaryReader r = new BinaryReader(fs);
 15             //时间戳
 16             string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
 17             byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "--\r\n");
 18             //请求头部信息
 19             StringBuilder sb = new StringBuilder();
 20             sb.Append("--");
 21             sb.Append(strBoundary);
 22             sb.Append("\r\n");
 23             sb.Append("Content-Disposition: form-data; name=\"");
 24             sb.Append("file");
 25             sb.Append("\"; filename=\"");
 26             sb.Append(fileName);
 27             sb.Append("\"");
 28             sb.Append("\r\n");
 29             sb.Append("Content-Type: ");
 30             sb.Append("application/octet-stream");
 31             sb.Append("\r\n");
 32             sb.Append("\r\n");
 33             string strPostHeader = sb.ToString();
 34             System.Console.Write(strPostHeader);
 35             System.Console.Write("文件内容....");
 36             System.Console.Write("\r\n--" + strBoundary + "--\r\n");
 37             byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
 38             // 根据uri创建HttpWebRequest对象
 39             HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
 40             httpReq.Method = "POST";
 41             //对发送的数据不使用缓存
 42             httpReq.AllowWriteStreamBuffering = false;
 43             //设置获得响应的超时时间(300秒)
 44             httpReq.Timeout = 300000;
 45             httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
 46             long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
 47             long fileLength = fs.Length;
 48             httpReq.ContentLength = length;//请求内容长度
 49             try
 50             {
 51                 //每次上传5M
 52                 int bufferLength = 1024 * 1024 * 5;
 53                 byte[] buffer = new byte[bufferLength];
 54                 //已上传的字节数
 55                 long offset = 0;
 56                 //开始上传时间
 57                 DateTime startTime = DateTime.Now;
 58                 int size = r.Read(buffer, 0, bufferLength);
 59                 Stream postStream = httpReq.GetRequestStream();
 60                 //发送请求头部消息
 61                 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
 62                 while (size > 0)
 63                 {
 64                     postStream.Write(buffer, 0, size);
 65                     offset += size;
 66                     
 67                     TimeSpan span = DateTime.Now - startTime;
 68                     double second = span.TotalSeconds;
 69                     lblTime.Text = "已用时:" + second.ToString("F2") + "";
 70                     if (second > 0.001)
 71                     {
 72                         lblSpeed.Text = " 平均速度:" + (offset / 1024 / second).ToString("0.00") + "KB/秒";
 73                     }
 74                     else
 75                     {
 76                         lblSpeed.Text = " 正在连接…";
 77                     }
 78                     lblState.Text = "已上传:" + (offset * 100.0 / length).ToString("F2") + "%";
 79                     lblSize.Text = (offset / 1048576.0).ToString("F2") + "M/" + (fileLength / 1048576.0).ToString("F2") + "M";
 80 
 81                     size = r.Read(buffer, 0, bufferLength);
 82                 }
 83                 //添加尾部的时间戳
 84                 postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
 85                 postStream.Close();
 86                 //获取服务器端的响应
 87                 WebResponse webResponse = httpReq.GetResponse();
 88                 Stream s = webResponse.GetResponseStream();
 89                 StreamReader sr = new StreamReader(s);
 90                 //读取服务器端返回的消息
 91                 returnValue = sr.ReadLine();
 92                 s.Close();
 93                 sr.Close();
 94                 
 95             }
 96             catch(Exception ex)
 97             {
 98                 returnValue = ex.Message + ex.StackTrace;
 99             }
100             finally
101             {
102                 fs.Close();
103                 r.Close();
104             }
105             return returnValue;
106         }