///<summary> ///向服务器发送请求 ///</summary> ///<param name="URL">请求地址</param> ///<param name="method">POST或GET</param> ///<param name="showProgress">是否显示上传进度</param> private void SendRequestData(string URL, string method, bool showProgress) { clientSocket = new TcpClient(); Uri URI = new Uri(URL); clientSocket.Connect(URI.Host, URI.Port); requestHeaders.Add("Host", URI.Host); byte[] request = GetRequestHeaders(method + " " + URI.PathAndQuery + " HTTP/1.1"); clientSocket.Client.Send(request); //若有实体内容就发送它 if (postStream != null) { byte[] buffer = new byte[SEND_BUFFER_SIZE]; int count = 0; Stream sm = clientSocket.GetStream(); postStream.Position = 0; UploadEventArgs e = new UploadEventArgs(); e.totalBytes = postStream.Length; System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();//计时器 timer.Start(); do { //如果取消就推出 if (isCanceled) { break; } //读取要发送的数据 count = postStream.Read(buffer, 0, buffer.Length); //发送到服务器 sm.Write(buffer, 0, count); //是否显示进度 if (showProgress) { //触发事件 e.bytesSent += count; e.sendProgress = (double)e.bytesSent / (double)e.totalBytes; double t = timer.ElapsedMilliseconds / 1000; t = t <= 0 ? 1 : t; e.sendSpeed = (double)e.bytesSent / t; if (UploadProgressChanged != null) { UploadProgressChanged(this, e); } } } while (count > 0); timer.Stop(); postStream.Close(); //postStream.Dispose(); postStream = null; }//end if }
/// <summary> /// upload files or image or text or .exe or .txt /// </summary> /// <param name="url"></param> /// <param name="file"></param> /// <param name="paramName"></param> /// <param name="contentType"></param> /// <param name="nvc"></param> /// <param name="headerItems"></param> public string HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) { // log.Debug(string.Format("Uploading {0} to {1}", file, url)); string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); wr.ContentType = "multipart/form-data; boundary=" + boundary; wr.Method = "POST"; wr.KeepAlive = true; wr.Credentials = System.Net.CredentialCache.DefaultCredentials; Stream rs = wr.GetRequestStream(); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; foreach (string key in nvc.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, nvc[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } rs.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, paramName, file, contentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[4096]; //4096 SEND_BUFFER_SIZE int bytesRead = 0; /// show upload file process UploadEventArgs e = new UploadEventArgs(); e.totalBytes = fileStream.Length; System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();//计时器 timer.Start(); /*do { //如果取消就推出 if (isCanceled) { break; } bytesRead = fileStream.Read(buffer, 0, buffer.Length); rs.Write(buffer, 0, bytesRead); //触发事件 e.bytesSent += bytesRead; e.sendProgress = (double)e.bytesSent / (double)e.totalBytes; double t = timer.ElapsedMilliseconds / 1000; t = t <= 0 ? 1 : t; e.sendSpeed = (double)e.bytesSent / t; if (UploadProgressChanged != null) { UploadProgressChanged(this, e); } } while (bytesRead > 0); */ while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); e.bytesSent += bytesRead; e.sendProgress = (double)e.bytesSent / (double)e.totalBytes; double t = timer.ElapsedMilliseconds / 1000; t = t <= 0 ? 1 : t; e.sendSpeed = (double)e.bytesSent / t; if (UploadProgressChanged != null) { UploadProgressChanged(this, e); } } timer.Stop(); fileStream.Close(); byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); rs.Close(); WebResponse wresp = null; try { wresp = wr.GetResponse(); Stream stream2 = wresp.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string endstr = reader2.ReadToEnd(); if (endstr != null) { return endstr; } //MessageBox.Show(string.Format("File uploaded, server response is:"+ reader2.ReadToEnd())); } catch (Exception ex) { // MessageBox.Show("Error uploading file"+ ex); if (wresp != null) { wresp.Close(); wresp = null; } return ""; } finally { wr = null; } return ""; }