Guzzle 6发送多部分数据

时间:2016-05-13 09:13:57

标签: php bdd behat guzzle

我想在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']
            ]]);

但我收到错误

  

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

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

谁知道我犯了哪个错误?

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

根据文档," 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']
        ]
    ]
]);