【问题标题】:HttpGuzzle 6, Post Request With Data and FileHttpGuzzle 6,使用数据和文件发布请求
【发布时间】:2019-05-07 01:25:13
【问题描述】:

我正在尝试发布一个带有文件和一些字段的请求,在我使用 Guzzle http v3 之前,下面的代码正在运行,

        $client = Client();
        $request = $client->request('POST', $url, ['headers' => ['Authorization' => 'auth_trusted_header')]]);

        /** @var \GuzzleHttp\Post\PostBody $body */
        $body = $request->getBody();
        $body->setField('authorId', $user->getId());
        $body->setField('context', 'avatar');
        $body->addFile(
            new PostFile(
                'file',
                fopen('data://text/plain;base64,'.$avatar, 'r'),
                $user->getId().'.png'
            )
        );
        try {
            $response = $client->send($request);
        } catch (\Exception $e) {
            $response = false;
        }

升级到 V6 后,我更新了下面的代码,但不知何故它不起作用....

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Request as GuzzleRequest;

        $client = new Client();
        $request = new GuzzleRequest('POST', $url, $this->genHeadersSettings(),
            [
                'multipart' => [
                    [
                        'Content-type' => 'multipart/form-data',
                        'name' => 'file',
                        'contents' => fopen('data://text/plain;base64,'.$avatar, 'r'),
                        'filename' => $user->getId().'.png',
                    ]
                ],
                'form_params' => [
                    'authorId' => $user->getId(),
                    'context' => 'avatar',
                    ]
            ]
        );

以上代码抛出Invalid resource type: array...

有什么办法吗?

【问题讨论】:

    标签: symfony curl guzzle php-7.2 guzzle6


    【解决方案1】:

    在这种情况下,您可能实际上并不想使用 PSR-7 界面,因为您是从旧版本的 Guzzle 转换而来的。您可能需要$client->request() 方法,它与旧的 Guzzle 请求样式大部分兼容,包括您在此处尝试的多部分帖子(请参阅http://docs.guzzlephp.org/en/stable/quickstart.html#post-form-requests)。

    如果你确实坚持要切换到 PSR-7 接口,那么你需要传入一个Psr\Http\Message\StreamInterface 对象或可以转换为流(如字符串)的东西,而不是数组。这是您收到的错误。

    【讨论】:

    • 我知道了You cannot use form_params and multipart at the same time. Use the form_params option if you want to send application/x-www-form-urlencoded requests, and the multipart option to send multipart/form-data requests.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多