ASP.NET上傳文件到遠程服務器(HttpWebRequest)

/// <summary>
     /// 文件上傳至遠程服務器
     /// </summary>
     /// <param name="url">遠程服務地址</param>
     /// <param name="postedFile">上傳文件</param>
     /// <param name="parameters">POST參數</param>
     /// <param name="cookieContainer">cookie</param>
     /// <param name="output">遠程服務器響應字符串</param>
     public static void HttpPostFile(string url,
                                     System.Web.HttpPostedFile postedFile,
                                     Dictionary<string, object> parameters,
                                     CookieContainer cookieContainer,
                                     ref string output)
     {
         //1>建立請求
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
         //2>Cookie容器
         request.CookieContainer = cookieContainer;
         request.Method = "POST";
         request.Timeout = 20000;
         request.Credentials = System.Net.CredentialCache.DefaultCredentials;
         request.KeepAlive = true;
 
         string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");//分界線
         byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
 
         request.ContentType = "multipart/form-data; boundary=" + boundary; ;//內容類型
 
         //3>表單數據模板
         string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
 
         //4>讀取流
         byte[] buffer = new byte[postedFile.ContentLength];
         postedFile.InputStream.Read(buffer, 0, buffer.Length);
 
         //5>寫入請求流數據
         string strHeader = "Content-Disposition:application/x-www-form-urlencoded; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
         strHeader = string.Format(strHeader,
                                  "filedata",
                                  postedFile.FileName,
                                  postedFile.ContentType);
         //6>HTTP請求頭
         byte[] byteHeader = System.Text.ASCIIEncoding.ASCII.GetBytes(strHeader);
         try
         {
             using (Stream stream = request.GetRequestStream())
             {
                 //寫入請求流
                 if (null != parameters)
                 {
                     foreach (KeyValuePair<string, object> item in parameters)
                     {
                         stream.Write(boundaryBytes, 0, boundaryBytes.Length);//寫入分界線
                         byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formdataTemplate, item.Key, item.Value));
                         stream.Write(formBytes, 0, formBytes.Length);
                     }
                 }
                 //6.0>分界線============================================注意:缺乏次步驟,可能致使遠程服務器沒法獲取Request.Files集合
                 stream.Write(boundaryBytes, 0, boundaryBytes.Length);
                 //6.1>請求頭
                 stream.Write(byteHeader, 0, byteHeader.Length);
                 //6.2>把文件流寫入請求流
                 stream.Write(buffer, 0, buffer.Length);
                 //6.3>寫入分隔流
                 byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                 stream.Write(trailer, 0, trailer.Length);
                 //6.4>關閉流
                 stream.Close();
             }
             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             using (StreamReader reader = new StreamReader(response.GetResponseStream()))
             {
                 output = reader.ReadToEnd();
             }
             response.Close();
         }
         catch (Exception ex)
         {
             throw new Exception("上傳文件時遠程服務器發生異常!", ex);
         }
     }
相關文章
相關標籤/搜索