Guzzle 6发送多部分数据


Guzzle 6 send multipart data

我想向Guzzle Http请求添加一些数据。有文件名、文件内容和带有授权密钥的头。

$this->request = $this->client->request('POST', 'url', [
    'multipart' => [
        'name' => 'image_file',
        'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
        'headers' =>
            ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
            ]]);

但是我得到错误

可捕获的致命错误:传递给GuzzleHttp''Psr7''MultipartStream::addElement()的参数2的类型必须为数组、字符串给定,在vendor ''guzzlehttp''psr7''src''MultipartStream.php第70行调用,并在vendor '' guzzlehttp''psr7''''src''MultipartStream.php第79行中定义

在Guzzle 6中,文档是这样的:http://docs.guzzlephp.org/en/latest/request-options.html#multipart

谁知道我哪里搞错了?

这是解决方案。具有访问令牌的标头应位于多部分节之外。

$this->request = $this->client->request('POST', 'request_url', [
            'headers' => [
                'Authorization' => 'Bearer access_token'
            ],
            'multipart' => [
                [
                    'Content-type' => 'multipart/form-data',
                    'name' => 'image_file',
                    'contents' => fopen('image_file_url', 'r')
                ]
            ]
        ]);

根据文档,"multipart的值是关联数组的数组",因此您需要嵌套更深一层:

$this->request = $this->client->request('POST', 'url', [
    'multipart' => [
        [
            'name' => 'image_file',
            'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
            'headers' => ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
        ]
    ]
]);

试试这个适用于我

use GuzzleHttp'Client;
use GuzzleHttp'Psr7'Utils;
$this->client = new Client([
        'base_uri' => 'https://baseurl'
    ]);
$body = Utils::tryFopen($tempPath . $fileName, 'r');
$res = $this->client->request(
                 'POST',
                 'url',
                  [
                     'headers' => [
                        ...
                     ],
                     'body' => $body
                  ]
            );