1. 程式人生 > >C# HTTP系列13 以form-data方式上傳多個檔案以及鍵值對集合到遠端伺服器

C# HTTP系列13 以form-data方式上傳多個檔案以及鍵值對集合到遠端伺服器

系列目錄     【已更新最新開發文章,點選檢視詳細】

類似於以下場景,將表單中的使用者資訊(包含附件)上傳到伺服器並儲存到資料庫中,

<form id="form1" runat="server" action="UserManageHandler.ashx" method="post" enctype="multipart/form-data">
    <div>
        名稱:  <input type="text" name="uname"   class="uname" /><br/>
        郵件:  <input type="text" name="email"   class="email" /><p/>
        附件1: <input type="file" name="file1"   class="file" /><p/>
        附件2: <input type="file" name="file2"   class="file" /><p/>
        附件3: <input type="file" name="file3"   class="file" /><p/>
               <input type="submit" name="submit" value="提交" />
    </div>
</form>

如果是在傳統的管理系統或者網站中,上傳到釋出的IIS站點下,使用ASP.NET的上傳控制元件結合後臺的 HttpContext.Request.Files的相關類與方法很簡單的即可實現上述功能。

1  HttpFileCollection files = HttpContext.Current.Request.Files;
2  HttpPostedFile postedFile = files["fileUpload"];
3  postedFile.SaveAs(postedFile.FileName);

隨著雲端應用的發展與普及,第三方應用平臺或者開發平臺部署在雲伺服器上,例如阿里雲、騰訊雲、七牛雲、青雲等。第三方對外開放的應用平臺大都是提供Restful API供開發者呼叫以上傳(本地或者遠端檔案)或下載業務資料進行業務開發。

multipart/form-data 資料格式介紹 1、使用Postman模擬上述功能(不上傳附件)

 點選【Code】按鈕,開啟如下窗體

 

2、只上傳一個附件

此點選【提交】按鈕,Form提交請求資料,Fiddler抓包時看到的請求如下(無關的請求頭在本文中都省略掉了):

 

3、上傳多個附件,一個普通文字,一個Office word文件,一個png圖片

此點選【提交】按鈕,Form提交請求資料,Fiddler抓包時看到的請求如下(無關的請求頭在本文中都省略掉了):

 

HTTP 請求中的 multipart/form-data,它會將表單的資料處理為一條訊息,以標籤為單元,用分隔符分開。既可以上傳鍵值對,也可以上傳檔案。當上傳的欄位是檔案時,會有Content-Type來表名檔案型別;content-disposition,用來說明欄位的一些資訊;

由於有 boundary 隔離,所以 multipart/form-data 既可以上傳檔案,也可以上傳鍵值對,它採用了鍵值對的方式,所以可以上傳多個檔案。

具體格式描述為:

(1)boundary:用於分割不同的欄位,為了避免與正文內容重複。以2個橫線“--”開頭,最後的欄位之後以2個橫線“--”結束。

(2)Content-Type: 指明瞭資料是以 multipart/form-data 來編碼。

(3)訊息主體裡按照欄位個數又分為多個結構類似的部分,

  • 每部分都是以 --boundary 開始,
  • 緊接著是內容描述資訊,
  • 然後是回車(換一行),
  • 最後是欄位具體內容(文字或二進位制)。如果傳輸的是檔案,還要包含檔名和檔案型別資訊。
  • 訊息主體最後以 --boundary-- 標示結束。

關於 multipart/form-data 的詳細定義,請檢視 RFC1867 與 RFC2045 。

這種方式一般用來上傳檔案,各大服務端語言對它也有著良好的支援。

上面提到的這兩種 POST 資料的方式,都是瀏覽器原生支援的,而且現階段標準中原生 <form> 表單也只支援這兩種方式(通過 <form> 元素的 enctype 屬性指定,預設為 application/x-www-form-urlencoded)。

C# 通用方法實現 multipart/form-data 方式上傳附件與請求引數 清楚了 multipart/form-data 的資料請求格式之後,使用C#的 HttpWebRequest 與 HttpWebResponse 類來模擬上述場景,具體程式碼如下:
  1 /// <summary>
  2 /// HTTP請求(包含多分部資料,multipart/form-data)。
  3 /// 將多個檔案以及多個引數以多分部資料表單方式上傳到指定url的伺服器
  4 /// </summary>
  5 /// <param name="url">請求目標URL</param>
  6 /// <param name="fileFullNames">待上傳的檔案列表(包含全路徑的完全限定名)。如果某個檔案不存在,則忽略不上傳</param>
  7 /// <param name="kVDatas">請求時表單鍵值對資料。</param>
  8 /// <param name="method">請求的方法。請使用 WebRequestMethods.Http 的列舉值</param>
  9 /// <param name="timeOut">獲取或設定 <see cref="M:System.Net.HttpWebRequest.GetResponse" /> 和
 10 ///                       <see cref="M:System.Net.HttpWebRequest.GetRequestStream" /> 方法的超時值(以毫秒為單位)。
 11 ///                       -1 表示永不超時
 12 /// </param>
 13 /// <returns></returns>
 14 public HttpResult UploadFormByMultipart(string url, string[] fileFullNames, NameValueCollection kVDatas = null, string method = WebRequestMethods.Http.Post, int timeOut = -1)
 15 {
 16     #region 說明
 17     /* 阿里雲文件:https://www.alibabacloud.com/help/zh/doc-detail/42976.htm
 18        C# 示例:   https://github.com/aliyun/aliyun-oss-csharp-sdk/blob/master/samples/Samples/PostPolicySample.cs?spm=a2c63.p38356.879954.18.7f3f7c34W3bR9U&file=PostPolicySample.cs
 19                    (C#示例中僅僅是把檔案中的文字內容當做 FormData 中的項,與檔案流是不一樣的。本方法展示的是檔案流,更通用)
 20       */
 21 
 22     /* 說明:multipart/form-data 方式提交檔案
 23      *     (1) Header 一定要有 Content-Type: multipart/form-data; boundary={boundary}。
 24      *     (2) Header 和bod y之間由 \r\n--{boundary} 分割。
 25      *     (3) 表單域格式 :Content-Disposition: form-data; name="{key}"\r\n\r\n
 26      *                   {value}\r\n
 27      *                   --{boundary}
 28      *     (4)表單域名稱大小寫敏感,如policy、key、file、OSSAccessKeyId、OSSAccessKeyId、Content-Disposition。
 29      *     (5)注意:表單域 file 必須為最後一個表單域。即必須放在最後寫。
 30      */
 31     #endregion
 32 
 33     #region ContentType 說明
 34     /* 該ContentType的屬性包含請求的媒體型別。分配給ContentType屬性的值在請求傳送Content-typeHTTP標頭時替換任何現有內容。
 35        
 36        要清除Content-typeHTTP標頭,請將ContentType屬性設定為null。
 37        
 38      * 注意:此屬性的值儲存在WebHeaderCollection中。如果設定了WebHeaderCollection,則屬性值將丟失。
 39      *      所以放置在Headers 屬性之後設定
 40      */
 41     #endregion
 42 
 43     #region Method 說明
 44     /* 如果 ContentLength 屬性設定為-1以外的任何值,則必須將 Method 屬性設定為上載資料的協議屬性。 */
 45     #endregion
 46 
 47     #region HttpWebRequest.CookieContainer 在 .NET3.5 與 .NET4.0 中的不同
 48     /* 請參考:https://www.crifan.com/baidu_emulate_login_for_dotnet_4_0_error_the_fisrt_two_args_should_be_string_type_0_1/ */
 49     #endregion
 50 
 51     HttpResult httpResult = new HttpResult();
 52 
 53     #region 校驗
 54 
 55     if (fileFullNames == null || fileFullNames.Length == 0)
 56     {
 57         httpResult.Status = HttpResult.STATUS_FAIL;
 58 
 59         httpResult.RefCode = (int)HttpStatusCode2.USER_FILE_NOT_EXISTS;
 60         httpResult.RefText = HttpStatusCode2.USER_FILE_NOT_EXISTS.GetCustomAttributeDescription();
 61 
 62         return httpResult;
 63     }
 64 
 65     List<string> lstFiles = new List<string>();
 66     foreach (string fileFullName in fileFullNames)
 67     {
 68         if (File.Exists(fileFullName))
 69         {
 70             lstFiles.Add(fileFullName);
 71         }
 72     }
 73 
 74     if (lstFiles.Count == 0)
 75     {
 76         httpResult.Status = HttpResult.STATUS_FAIL;
 77 
 78         httpResult.RefCode = (int)HttpStatusCode2.USER_FILE_NOT_EXISTS;
 79         httpResult.RefText = HttpStatusCode2.USER_FILE_NOT_EXISTS.GetCustomAttributeDescription();
 80 
 81         return httpResult;
 82     }
 83 
 84     #endregion
 85 
 86     string boundary = CreateFormDataBoundary();                                       // 邊界符
 87     byte[] beginBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");     // 邊界符開始。【☆】右側必須要有 \r\n 。
 88     byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); // 邊界符結束。【☆】兩側必須要有 --\r\n 。
 89     byte[] newLineBytes = Encoding.UTF8.GetBytes("\r\n"); //換一行
 90     MemoryStream memoryStream = new MemoryStream();
 91 
 92     HttpWebRequest httpWebRequest = null;
 93     try
 94     {
 95         httpWebRequest = WebRequest.Create(url) as HttpWebRequest; // 建立請求
 96         httpWebRequest.ContentType = string.Format(HttpContentType.MULTIPART_FORM_DATA + "; boundary={0}", boundary);
 97         //httpWebRequest.Referer = "http://bimface.com/user-console";
 98         httpWebRequest.Method = method;
 99         httpWebRequest.KeepAlive = true;
100         httpWebRequest.Timeout = timeOut;
101         httpWebRequest.UserAgent = GetUserAgent();
102 
103         #region 步驟1:寫入鍵值對
104         if (kVDatas != null)
105         {
106             string formDataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n" +
107                                       "{1}\r\n";
108 
109             foreach (string key in kVDatas.Keys)
110             {
111                 string formItem = string.Format(formDataTemplate, key.Replace(StringUtils.Symbol.KEY_SUFFIX, String.Empty), kVDatas[key]);
112                 byte[] formItemBytes = Encoding.UTF8.GetBytes(formItem);
113 
114                 memoryStream.Write(beginBoundaryBytes, 0, beginBoundaryBytes.Length); // 1.1 寫入FormData項的開始邊界符
115                 memoryStream.Write(formItemBytes, 0, formItemBytes.Length);           // 1.2 將鍵值對寫入FormData項中
116             }
117         }
118         #endregion
119 
120         #region 步驟2:寫入檔案(表單域 file 必須為最後一個表單域)
121 
122         const string filePartHeaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
123                                               "Content-Type: application/octet-stream\r\n\r\n";
124 
125         int i = 0;
126         foreach (var fileFullName in lstFiles)
127         {
128             FileInfo fileInfo = new FileInfo(fileFullName);
129             string fileName = fileInfo.Name;
130 
131             string fileHeaderItem = string.Format(filePartHeaderTemplate, "file", fileName);
132             byte[] fileHeaderItemBytes = Encoding.UTF8.GetBytes(fileHeaderItem);
133 
134             if (i > 0)
135             {
136                 // 第一筆及第一筆之後的資料項之間要增加一個換行 
137                 memoryStream.Write(newLineBytes, 0, newLineBytes.Length);
138             }
139             memoryStream.Write(beginBoundaryBytes, 0, beginBoundaryBytes.Length);      // 2.1 寫入FormData項的開始邊界符
140             memoryStream.Write(fileHeaderItemBytes, 0, fileHeaderItemBytes.Length);    // 2.2 將檔案頭寫入FormData項中
141 
142             int bytesRead;
143             byte[] buffer = new byte[1024];
144 
145             FileStream fileStream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read);
146             while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
147             {
148                 memoryStream.Write(buffer, 0, bytesRead);                              // 2.3 將檔案流寫入FormData項中
149             }
150 
151             i++;
152         }
153 
154         memoryStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);             // 2.4 寫入FormData的結束邊界符
155 
156         #endregion
157 
158         #region 步驟3:將表單域(記憶體流)寫入 httpWebRequest 的請求流中,併發起請求
159         httpWebRequest.ContentLength = memoryStream.Length;
160 
161         Stream requestStream = httpWebRequest.GetRequestStream();
162 
163         memoryStream.Position = 0;
164         byte[] tempBuffer = new byte[memoryStream.Length];
165         memoryStream.Read(tempBuffer, 0, tempBuffer.Length);
166         memoryStream.Close();
167 
168         requestStream.Write(tempBuffer, 0, tempBuffer.Length);        // 將記憶體流中的位元組寫入 httpWebRequest 的請求流中
169         requestStream.Close();
170         #endregion
171 
172         HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; // 獲取響應
173         if (httpWebResponse != null)
174         {
175             //GetHeaders(ref httpResult, httpWebResponse);
176             GetResponse(ref httpResult, httpWebResponse);
177             httpWebResponse.Close();
178         }
179     }
180     catch (WebException webException)
181     {
182         GetWebExceptionResponse(ref httpResult, webException);
183     }
184     catch (Exception ex)
185     {
186         GetExceptionResponse(ref httpResult, ex, method, HttpContentType.MULTIPART_FORM_DATA);
187     }
188     finally
189     {
190         if (httpWebRequest != null)
191         {
192             httpWebRequest.Abort();
193         }
194     }
195 
196     return httpResult;
197 }

 請嚴格注意程式碼中註釋部分,尤其是以 boundary 作為分界線的部分,一點格式都不能錯誤,否則就無法提交成功。

 根據上述方法,可以衍生出幾個過載方法:

上傳單檔案與多個鍵值對

 1 /// <summary>
 2 /// HTTP請求(包含多分部資料,multipart/form-data)。
 3 /// 將檔案以及多個引數以多分部資料表單方式上傳到指定url的伺服器
 4 /// </summary>
 5 /// <param name="url">請求目標URL</param>
 6 /// <param name="fileFullName">待上傳的檔案(包含全路徑的完全限定名)</param>
 7 /// <param name="kVDatas">請求時表單鍵值對資料。</param>
 8 /// <param name="method">請求的方法。請使用 WebRequestMethods.Http 的列舉值</param>
 9 /// <param name="timeOut">獲取或設定 <see cref="M:System.Net.HttpWebRequest.GetResponse" /> 和
10 ///                       <see cref="M:System.Net.HttpWebRequest.GetRequestStream" /> 方法的超時值(以毫秒為單位)。
11 ///                       -1 表示永不超時
12 /// </param>
13 /// <returns></returns>
14 public HttpResult UploadFormByMultipart(string url, string fileFullName, NameValueCollection kVDatas = null, string method = WebRequestMethods.Http.Post, int timeOut = -1)
15 {
16     string[] fileFullNames = { fileFullName };
17 
18     return UploadFormByMultipart(url, fileFullNames, kVDatas, method, timeOut);
19 }
 1 /// <summary>
 2 /// HTTP請求(包含多分部資料,multipart/form-data)。
 3 /// 將檔案以多分部資料表單方式上傳到指定url的伺服器
 4 /// </summary>
 5 /// <param name="url">請求目標URL</param>
 6 /// <param name="fileFullName">待上傳的檔案(包含全路徑的完全限定名)</param>
 7 /// <param name="kVDatas">請求時表單鍵值對資料。</param>
 8 /// <param name="method">請求的方法。請使用 WebRequestMethods.Http 的列舉值</param>
 9 /// <param name="timeOut">獲取或設定 <see cref="M:System.Net.HttpWebRequest.GetResponse" /> 和
10 ///                       <see cref="M:System.Net.HttpWebRequest.GetRequestStream" /> 方法的超時值(以毫秒為單位)。
11 ///                       -1 表示永不超時
12 /// </param>
13 /// <returns></returns>
14 public HttpResult UploadFormByMultipart(string url, string fileFullName, Dictionary<string, string> kVDatas = null, string method = WebRequestMethods.Http.Post, int timeOut = -1)
15 {
16     var nvc = kVDatas.ToNameValueCollection();
17     return UploadFormByMultipart(url, fileFullName, nvc, method, timeOut);
18 }

 

系列目錄     【已更新最新開發文章,點選檢視詳細