【问题标题】:Proper formatting of a JSON and multiplepart Guzzle post requestJSON 和多部分 Guzzle 发布请求的正确格式
【发布时间】:2019-09-13 07:11:13
【问题描述】:

我有两个不同的 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 发布请求。

【问题讨论】:

    标签: laravel post laravel-5 guzzle


    【解决方案1】:

    你可以试试这个:

    $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,
    ]);
    

    【讨论】:

    • 我给了你一个测试,但是出现了一个语法错误,集中在 multipart[] 的结束框括号和它之后的逗号(以及结束大括号之前),说逗号是意外的.我尝试将其删除,但最后的大括号出现了问题。为了澄清起见,我还修复了 $doc->type_id 之后的撇号。
    • “我给了你一个测试,但是出现了一个语法错误,集中在结束框括号上” - 我复制了你的代码,虽然你的代码可能也不起作用:) 无论如何,我做了一个编辑
    猜你喜欢
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2022-02-21
    • 2012-06-24
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多