正确格式化JSON和多部分Guzzle发布请求

问题描述 投票:0回答:1

我有两个不同的Guzzle帖子请求,我试图合并(仅仅因为他们基本上做一个统一的工作,应该一起执行)。

最初我有我的捐赠数据:

'donation' => [
       'web_id' => $donation->web_id,
       'amount' => $donation->amount,
       'type' => $donation->type,
       'date' => $donation->date->format('Y-m-d'),
       'collection_id' => NULL,
       'status_id' => $donation->status_id,
 ],

然后我有我的文件,它们基本上是为捐赠者启用或禁用的两个不同的PDF,有时它们都有。我知道多部分看起来像下面,但我不确定。

                foreach ($uploadDocs as $doc) {
                        'multipart' => [
                            [
                                'name'     => 'donation_id',
                                'contents' => $donation->web_id,
                            ],
                            [
                                'name'     => 'type_id',
                                'contents' => $doc->type_id',
                            ],
                            [
                                'name'     => 'file',
                                'contents' => fopen($doc->path, 'r'),
                                'headers'  => ['Content-Type' => 'application/pdf'],
                            ],
                        ],
                }

由于我通常一次只处理一个文件而且我不确定如何将第一个代码块与第二个代码段合并以获得适当的Guzzle post请求。

laravel post laravel-5 guzzle
1个回答
0
投票

你可以试试这个:

$donationData = [
    'web_id' => $donation->web_id,
    'amount' => $donation->amount,
    'type' => $donation->type,
    'date' => $donation->date->format('Y-m-d'),
    'collection_id' => NULL,
    'status_id' => $donation->status_id,
];

$multipart = [];

foreach ($uploadDocs as $doc) {
    $multipart[] = [
        [
            'name'     => 'donation_id',
            'contents' => $donation->web_id,
        ],
        [
            'name'     => 'type_id',
            'contents' => $doc->type_id,
        ],
        [
            'name'     => 'file',
            'contents' => fopen($doc->path, 'r'),
            'headers'  => ['Content-Type' => 'application/pdf'],
        ],
    ];
}

比执行您的请求:

$r = $client->request('POST', 'http://example.com', [
    'body' => $donationData,
    'multipart' => $multipart,
]);
© www.soinside.com 2019 - 2024. All rights reserved.