【问题标题】:Post Multipart and Json together with Guzzle in Laravel在 Laravel 中将 Multipart 和 Json 与 Guzzle 一起发布
【发布时间】:2017-10-11 07:54:08
【问题描述】:

我正在尝试使用 Guzzle 发布多部分和 json 数据,以使用 Phonegap Build API 构建我的应用程序。我已经尝试了很多调整,但仍然得到错误结果。这是我正在使用的最新功能:

public function testBuild(Request $request)
{
     $zip_path = storage_path('zip/testing.zip');
     $upload = $this->client->request('POST', 'apps',
          ['json' =>
            ['data' => array(
              'title'         => $request->title,
              'create_method' => 'file',
              'share'         => 'true',
              'private'       => 'false',
            )],
           'multipart' => 
            ['name'           => 'file',
             'contents'       => fopen($zip_path, 'r')
            ]
          ]);
      $result = $upload->getBody();
      return $result;
}

这是我从 API 获得成功结果的正确 curl 格式,但我的桌面上有文件:

curl -F file=@/Users/dedenbangkit/Desktop/testing.zip 
-u email@email.com 
-F 'data={"title":"API V1 App","version":"0.1.0","create_method":"file"}'
 https://build.phonegap.com/api/v1/apps

【问题讨论】:

标签: laravel phonegap-build guzzle


【解决方案1】:

如前所述,您不能同时使用multipartjson

在您的 curl 示例中,它只是一个多部分表单,因此在 Guzzle 中使用相同的形式:

$this->client->request('POST', 'apps', [
    'multipart' => [
        [
            'name' => 'file',
            'contents' => fopen($zip_path, 'r'),
        ],
        [
            'name' => 'data',
            'contents' => json_encode(
                [
                    'title' => $request->title,
                    'create_method' => 'file',
                    'share' => 'true',
                    'private' => 'false',
                ]
            ),
        ]
    ]
]);

【讨论】:

  • 谢谢,您的代码对我有用。但是为什么数组对内容数据不起作用?
  • 因为contents (简单)是一个字节数组。 Guzzle 中的json 只是一个小帮手,它为你做json_encode(),但它只适用于“简单”的身体,多部分选项没有这样的帮手。
  • 明白了,现在我明白了 guzzle 的工作原理。非常感谢!
猜你喜欢
  • 2019-12-08
  • 2019-05-31
  • 2021-12-26
  • 2019-06-17
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
  • 2017-11-15
  • 2017-12-20
相关资源
最近更新 更多