请问哪份 RFC 文档定义了 multipart/form-data 的格式?


请问哪份 RFC 文档定义了 multipart/form-data 的格式?

需求:同时上传多个 zip 文件。
问题:该如何构造 multipart/form-data 类型的 Entity 。
补充:我搜到 Returning Values from Forms: multipart/form-data ,扫了一眼还没找到定义格式的内容。

http post

大脸兔喷喷 9 years, 9 months ago
O4LOVE answered 9 years, 9 months ago

https://www.ietf.org/rfc/rfc1867.txt

手动构造示例(PHP):


 <?php

/**
 * @param string $url
 * @param array $paramArr {"form_name":"form_value"}
 * @param array $fileArr {"form_name":{"name":"file_name", "data":"file_data", "type":"file_type"}}
 * @return array
 */
function urlMultiPartPost($url, $paramArr, $fileArr)
{
    $ch = curl_init("$url");
    $body = array() ;
    foreach ($paramArr as $k => $v) {
        $formData = array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v),
        ) ;
        $body[] = implode("\r\n", $formData);
    }

    foreach ($fileArr as $k => $v) {
        $formData = array(
            "Content-Disposition: form-data; name=\"$k\"; filename=\"{$v["name"]}\"",
            "Content-Type: {$v["type"]}",
            "",
            $v["data"],
        ) ;
        $body[] = implode("\r\n", $formData);
    }

    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));
    // add boundary for each file parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });
    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";

    curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_RETURNTRANSFER => 1 ,
        CURLOPT_HTTPHEADER => array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    return $response;
}

当然,PHP里几乎没有手动构造的必要……

呆萌総大将 answered 9 years, 9 months ago

Your Answer