【问题标题】:How do I make a cURL post which sends both JSON data and a binary file?如何制作同时发送 JSON 数据和二进制文件的 cURL 帖子?
【发布时间】:2013-05-13 23:53:25
【问题描述】:

我正在尝试创建一个 PHP 脚本,它将一些 JSON 数据与压缩文件一起发送到 API (InMobi),但我无法让它工作。我通常只是将标头设置为 application/json 并使用 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); 其中 $data 是一个 PHP 数组,但怎么做我在上面附加文件?

请求应如下所示:

Content-Type: multipart/form-data; boundary=AYip2bnLbOw0R2vf8lDZ71pon3CDottfPlckt-E Content-Disposition: form-data; name="payload"
Content-Type: application/json; charset=US-ASCII
Content-Transfer-Encoding: 8bit
{
    "campaign": {
        "name": "campaign-with-banner-ad",
        "dailyBudget": "2000.00",
        "startDate": "2012-03-10",
        "endDate": "2012-05-31",
        "action": "create",
        "adGroups": [
            {
                "countryId": 94,
                "name": "First AdGroup",
                "bid": "1.89",
                "landingURL": "http://test.inmobi.com/sampleapp",
                "ctaDetails": {
                    "id": "1"
                },
                "action": "create",
                "ads": [
                    {
                        "type": "banner",
                        "name": "From Root",
                        "filePath": "/",
                        "altText": "3 img add",
                        "action": "create"
                    },
                    {
                        "type": "banner",
                        "name": "From ad1",
                        "filePath": "/ad1/",
                        "action": "create"
                    },
                    {
                        "type": "banner",
                        "name": "From ad2",
                        "filePath": "/ad2/",
                        "action": "create"
                    }
                ]
            }
        ]
    }
}
--AYip2bnLbOw0R2vf8lDZ71pon3CDottfPlckt-E
Content-Disposition: form-data; name="zipFile"; filename="banners.zip" Content-Type: application/octet-stream; charset=ISO-8859-1
Content-Transfer-Encoding: binary

<Contents of ZIP File>

在我看到的所有示例中,他们将文件放在 CURLOPT_POSTFIELDS 中,但我不知道如何将其与 json_encode 结合起来,并且上述请求看起来文件是在请求的单独部分中发送的。

谢谢!

【问题讨论】:

    标签: php curl


    【解决方案1】:

    将数据分成两个字段:

    $postdata = array(
        'json' => json_encode($whatever),
        'zipfile' => '@/path/to/yourfile.zip'
    );
    
    curl_setopt($curl, CURLOPT_POST_FIELDS, $postdata);
    

    然后在接收端:

    $json = json_decode($_POST['json');
    $file = $_FILES['zipfile'];
    

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 2014-01-23
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      相关资源
      最近更新 更多