[ laravel爬虫实战--进阶篇 ] guzzle实现多张图片上传

Song792 次浏览0个评论2023年01月14日

POST/表单请求

除了使用 body 参数来指定请求数据外,Guzzle为发送POST数据提供了有用的方法。

发送表单字段

发送 application/x-www-form-urlencoded POST请求需要你传入 form_params 数组参数,数组内指定POST的字段。

$response = $client->request('POST', 'http://httpbin.org/post', [
    'form_params' => [
        'field_name' => 'abc',
        'other_field' => '123',
        'nested_field' => [
            'nested' => 'hello'
        ]
    ]
]);

发送表单文件

你可以通过使用 multipart 请求参数来发送表单(表单enctype属性需要设置 multipart/form-data )文件, 该参数接收一个包含多个关联数组的数组,每个关联数组包含一下键名:

  • name: (必须,字符串) 映射到表单字段的名称。
  • contents: (必须,混合) 提供一个字符串,可以是 fopen 返回的资源、或者一个

Psr\Http\Message\StreamInterface 的实例。

$response = $client->request('POST', 'http://httpbin.org/post', [
    'multipart' => [
        [
            'name'     => 'field_name',
            'contents' => 'abc'
        ],
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'other_file',
            'contents' => 'hello',
            'filename' => 'filename.txt',
            'headers'  => [
                'X-Foo' => 'this is an extra header to include'
            ]
        ]
    ]
]);


演示案例

上传多图案例

$images = $request->file('images');

    foreach ($images as $image)
    {
        $body[] = [
            'Content-type' => 'multipart/form-data',
            'name'         => $image->getClientOriginalName(),
            'contents'     => fopen($image->getRealPath(), 'r')
        ];
    }

    $data = $request->all();
    $client = new Client();

    $response = $client->request('POST', $url, [
        'multipart' => $body,
        'json'      => $data
    ]);

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文