Http协议中的数据传送之多重表单提交--multipart/form-data
RFC 2188: Returning Values from Forms: multipart/form-data,這份文件說明了在 HTTP POST 訊息中使用多種格式信息的作法,它可以用在許多 REST-based API 的系統,它可以混合多種資料格式并一次傳送,當然非文字的資料必須要編碼為二進制字符串。
在 RFC 2387 文件中,指出若要傳輸多種參數,多種資料型態混合的信息時,要先將 HTTP 要求的 Content-Type 設為 multipart/form-data,而且要設定一個 boundary 參數,這個參數是由應用程序自行產生,它會用來識別每一份資料的邊界 (boundary),用以產生多重信息部份 (message part),而 HTTP 服務器可以抓取 HTTP POST 的信息,并且以慣用的對象模型來暴露給服務器讀取 (ex: ASP.NET 的 Request.Form)。
下面是一個多重參數的 multipart/form-data 的訊息 (source: RFC 2388):
Content-Type: multipart/form-data; boundary=MYBOUNDARY
…
--MYBOUNDARY
Content-Disposition: form-data; name="[PARAMETER-NAME]"
<NEWLINE>
<NEWLINE>
<Data goes here>
--MYBOUNDARY
Content-Disposition: form-data; name="[PARAMETER-NAME]"
<NEWLINE>
<NEWLINE>
<Data goes here>
--MYBOUNDARY
Content-Disposition: form-data; name="[PARAMETER-NAME]"
Content-Type: image/jpeg
<NEWLINE>
<NEWLINE>
<Image data goes here>
--MYBOUNDARY
上面的信息看起來還蠻難懂的,不過它的幾個基本概念是:
1. 每個信息部份都要用 --[BOUNDARY_NAME] 來包裝,以分隔出信息的每個部份,而最后要再加上一個 --[BOUNDARY_NAME] 來表示結束。
2. 每個信息部份都要有一個 Content-Disposition: form-data; name="",而 name 設定的就是 HTTP POST 的鍵值 (key)。
3. 聲明區和值區中間要隔兩個新行符號 (以 .NET 來說,就是 Environment.NewLine)。
4. 中間可以夾入二進制資料,但二進制資料必須要格式化為二進制字符串,這個工作會由 HttpWebRequest 在使用 NetworkStream.Write() 寫入上傳資料時自動由系統去掉。
5. 若要設定不同信息段的資料型別 (Content-Type),則要在信息段內的聲明區設定。
只要了解了資料格式,就能夠寫程序來生成它:
public static byte[] BuildMultipartPostData(string Boundary, Dictionary<string, string> HttpPostData, PostFileData FileUploadData)
{
??? StringBuilder sb = new StringBuilder();
??? // append access token.
??? sb.AppendLine("--" + Boundary);
??? sb.Append(Environment.NewLine);?
??? // append form part.
??? if (HttpPostData != null && HttpPostData.Count > 0)
??? {
??????? foreach (KeyValuePair<string, string> HttpPostDataItem in HttpPostData)
??????? {
??????????? sb.AppendLine("--" + Boundary);
??????????? sb.AppendLine(string.Format("Content-Disposition: form-data;name=\"{0}\"", HttpPostDataItem.Key));
??????????? sb.Append(Environment.NewLine);
??????????? sb.AppendLine(HttpPostDataItem.Value);
??????? }
??? }
??? // handle file upload.
??? if (FileUploadData != null)
??? {
??????? sb.AppendLine("--" + Boundary);
??????? sb.AppendLine(string.Format("Content-Disposition: form-data;name=\"{0}\"; filename=\"{1}\"", FileUploadData.Name, FileUploadData.FileName));
??????? sb.AppendLine(string.Format("Content-Type: {0}", FileUploadData.ContentType));
??????? sb.Append(Environment.NewLine);
??? }
??? MemoryStream ms = new MemoryStream();
??? BinaryWriter bw = new BinaryWriter(ms);
??? bw.Write(Encoding.Default.GetBytes(sb.ToString()));
??? bw.Write(FileUploadData.FileData);
??? bw.Write(Encoding.Default.GetBytes(Environment.NewLine));
??? bw.Write(Encoding.Default.GetBytes("--" + Boundary));
??? ms.Flush();
??? ms.Position = 0;
??? byte[] result = ms.ToArray();
??? bw.Close();
??? return result;
}
而實際發送的程序就無需特別的修改,但唯一要注意的是要加上 boundary 參數,否則多個信息部份的能力會無法使用。
public static string MakeHttpPost(string RequestUrl, Dictionary<string, string> HttpPostData, PostFileData FileUploadData)
{
??? HttpWebRequest request = WebRequest.Create(RequestUrl) as HttpWebRequest;
??? HttpWebResponse response = null;
??? StreamReader sr = null;
??? string boundary = "FBGraphAPIClient" + DateTime.Now.Ticks.ToString();
??? try
??? {
??????? request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
??????? byte[] multipartPostData = Helpers.BuildMultipartPostData(boundary, HttpPostData, FileUploadData);
??????? BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
??????? bw.Write(multipartPostData);
??????? bw.Close();
??????? response = request.GetResponse() as HttpWebResponse;
??????? sr = new StreamReader(response.GetResponseStream());
??????? string responseData = sr.ReadToEnd();
??????? sr.Close();
??????? response.Close();
??????? return responseData;
??? }
??? catch (WebException we)
??? {
??????? throw new APIException((we.Response as HttpWebResponse));
??? }
??? catch (Exception)
??? {
??????? throw;
??? }
}
Reference:
1. RFC 2388
2、http://code.msdn.microsoft.com/ASPNET-Web-API-File-Upload-a8c0fb0d
3、http://stackoverflow.com/questions/12593001/web-api-model-binding-with-multipart-formdata
4、http://lonetechie.com/2012/09/23/web-api-generic-mediatypeformatter-for-file-upload/
5、http://www.cnblogs.com/hun_dan/archive/2012/04/09/2438709.html
轉載于:https://www.cnblogs.com/shanyou/archive/2013/06/07/3123155.html
總結
以上是生活随笔為你收集整理的Http协议中的数据传送之多重表单提交--multipart/form-data的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php批量缩放图片
- 下一篇: CSS样式中” 大于号”