系列目錄???? 【已更新最新開發(fā)文章,點擊查看詳細】
<https://www.cnblogs.com/SavionZhang/p/11422481.html>
類似于以下場景,將表單中的用戶信息(包含附件)上傳到服務器并保存到數(shù)據(jù)庫中,
<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: <
inputtype="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>
如果是在傳統(tǒng)的管理系統(tǒng)或者網(wǎng)站中,上傳到發(fā)布的IIS站點下,使用ASP.NET的上傳控件結(jié)合后臺的
HttpContext.Request.Files的相關類與方法很簡單的即可實現(xiàn)上述功能。
1 HttpFileCollection files = HttpContext.Current.Request.Files; 2
HttpPostedFile postedFile = files["fileUpload"]; 3
postedFile.SaveAs(postedFile.FileName);
隨著云端應用的發(fā)展與普及,第三方應用平臺或者開發(fā)平臺部署在云服務器上,例如阿里云、騰訊云、七牛云、青云等。第三方對外開放的應用平臺大都是提供Restful
API供開發(fā)者調(diào)用以上傳(本地或者遠端文件)或下載業(yè)務數(shù)據(jù)進行業(yè)務開發(fā)。
multipart/form-data 數(shù)據(jù)格式介紹 1、使用Postman模擬上述功能(不上傳附件)
?點擊【Code】按鈕,打開如下窗體
?
2、只上傳一個附件
此點擊【提交】按鈕,F(xiàn)orm提交請求數(shù)據(jù),F(xiàn)iddler抓包時看到的請求如下(無關的請求頭在本文中都省略掉了):
?
3、上傳多個附件,一個普通文本,一個Office word文檔,一個png圖片
此點擊【提交】按鈕,F(xiàn)orm提交請求數(shù)據(jù),F(xiàn)iddler抓包時看到的請求如下(無關的請求頭在本文中都省略掉了):
?
HTTP 請求中的
multipart/form-data,它會將表單的數(shù)據(jù)處理為一條消息,以標簽為單元,用分隔符分開。既可以上傳鍵值對,也可以上傳文件。當上傳的字段是文件時,會有Content-Type來表名文件類型;content-disposition,用來說明字段的一些信息;
由于有 boundary 隔離,所以 multipart/form-data 既可以上傳文件,也可以上傳鍵值對,它采用了鍵值對的方式,所以可以上傳多個文件。
具體格式描述為:
(1)boundary:用于分割不同的字段,為了避免與正文內(nèi)容重復。以2個橫線“--”開頭,最后的字段之后以2個橫線“--”結(jié)束。
(2)Content-Type: 指明了數(shù)據(jù)是以 multipart/form-data 來編碼。
(3)消息主體里按照字段個數(shù)又分為多個結(jié)構(gòu)類似的部分,
* 每部分都是以?--boundary?開始,
* 緊接著是內(nèi)容描述信息,
* 然后是回車(換一行),
* 最后是字段具體內(nèi)容(文本或二進制)。如果傳輸?shù)氖俏募€要包含文件名和文件類型信息。
* 消息主體最后以?--boundary--?標示結(jié)束。
關于 multipart/form-data 的詳細定義,請查看 RFC1867 <https://www.ietf.org/rfc/rfc1867.txt>
?與RFC2045 <https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4> 。
這種方式一般用來上傳文件,各大服務端語言對它也有著良好的支持。
上面提到的這兩種 POST 數(shù)據(jù)的方式,都是瀏覽器原生支持的,而且現(xiàn)階段標準中原生 <form> 表單也只支持這兩種方式
<http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4>(通過 <form> 元素的?
enctype?屬性指定,默認為?application/x-www-form-urlencoded)。
C# 通用方法實現(xiàn) multipart/form-data 方式上傳附件與請求參數(shù) 清楚了 multipart/form-data
的數(shù)據(jù)請求格式之后,使用C#的 HttpWebRequest 與?HttpWebResponse 類來模擬上述場景,具體代碼如下: 1 ///
<summary> 2 /// HTTP請求(包含多分部數(shù)據(jù),multipart/form-data)。 3 ///
將多個文件以及多個參數(shù)以多分部數(shù)據(jù)表單方式上傳到指定url的服務器 4 /// </summary> 5 /// <param name="url">
請求目標URL</param> 6 /// <param name="fileFullNames">
待上傳的文件列表(包含全路徑的完全限定名)。如果某個文件不存在,則忽略不上傳</param> 7 /// <param name="kVDatas">
請求時表單鍵值對數(shù)據(jù)。</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#示例中僅僅是把文件中的文本內(nèi)容當做 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屬性的值在請求發(fā)送Content-typeHTTP標頭時替換任何現(xiàn)有內(nèi)容。 35
36 要清除Content-typeHTTP標頭,請將ContentType屬性設置為null。 37 38 *
注意:此屬性的值存儲在WebHeaderCollection中。如果設置了WebHeaderCollection,則屬性值將丟失。 39 *
所以放置在Headers 屬性之后設置 40 */ 41 #endregion 42 43 #region Method 說明 44 /* 如果
ContentLength 屬性設置為-1以外的任何值,則必須將 Method 屬性設置為上載數(shù)據(jù)的協(xié)議屬性。*/ 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"); // 邊界符開始?!尽睢坑覀?cè)必須要有 \r\n 。 88
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"
);// 邊界符結(jié)束?!尽睢績蓚?cè)必須要有 --\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; // 創(chuàng)建請求 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 // 第一筆及第一筆之后的數(shù)據(jù)項之間要增加一個換行 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的結(jié)束邊界符 155 156 #endregion 157 158 #region 步驟3:將表單域(內(nèi)存流)寫入
httpWebRequest 的請求流中,并發(fā)起請求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); // 將內(nèi)存流中的字節(jié)寫入
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 作為分界線的部分,一點格式都不能錯誤,否則就無法提交成功。
?根據(jù)上述方法,可以衍生出幾個重載方法:
上傳單文件與多個鍵值對
1 /// <summary> 2 /// HTTP請求(包含多分部數(shù)據(jù),multipart/form-data)。 3 ///
將文件以及多個參數(shù)以多分部數(shù)據(jù)表單方式上傳到指定url的服務器 4 /// </summary> 5 /// <param name="url">
請求目標URL</param> 6 /// <param name="fileFullName">待上傳的文件(包含全路徑的完全限定名)</param> 7
/// <param name="kVDatas">請求時表單鍵值對數(shù)據(jù)。</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請求(包含多分部數(shù)據(jù),multipart/form-data)。 3 ///
將文件以多分部數(shù)據(jù)表單方式上傳到指定url的服務器 4 /// </summary> 5 /// <param name="url">請求目標URL
</param> 6 /// <param name="fileFullName">待上傳的文件(包含全路徑的完全限定名)</param> 7 ///
<param name="kVDatas">請求時表單鍵值對數(shù)據(jù)。</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 }
?
系列目錄???? 【已更新最新開發(fā)文章,點擊查看詳細】
<https://www.cnblogs.com/SavionZhang/p/11422481.html>
熱門工具 換一換