Fork me on GitHub

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

posted @ 2013-06-07 07:23  张善友  阅读(18173)  评论(3编辑  收藏  举报