[ laravel爬虫实战--进阶篇 ] guzzle实现多张图片上传
Song •
2098 次浏览 •
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
]);
更多相关好文
-
moment获取本月/本周/本年/上月/上周、或者指定日期的第一天/最后一天 2022-12-23 -
jQuery 密码验证 字母加数字或符号的组合密码,不能单独使用数字、字母或字符及 常用正则 2022-12-13 -
jquery正则表达式验证(手机号、身份证号、中文名称、数字) 2022-12-13 -
Laravel 出现 Packets out of order. Expected 1 received 0. Packet size=103 2022-12-02 -
ubuntu环境lnmp系统修改上传文件限制解决413 Request Entity Too Large 2022-11-07

花生壳绑定ubuntu服务器?