[ laravel爬虫实战--进阶篇 ] guzzle实现多张图片上传
Song •
1218 次浏览 •
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
]);
更多相关好文
-
laravel中distinct()的使用方法与去重 2017-09-11
-
Laravel将view缓存为静态html,laravel页面静态缓存 2021-10-09
-
[ laravel爬虫实战--基础篇 ] guzzle描述与安装 2017-11-01
-
[ 配置教程 ] 在ubuntu16.04中部署LNMP环境(php7+maridb且开启maridb远程以及nginx多域名访问 )并配置laravel环境 2017-07-18
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
热门文章
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
-
Mac 安装mysql并且配置密码 2024-11-20
-
阿里云不同账号(跨账号)ECS服务器同地域如何实现免费内网互通? 2024-11-12
-
electron安装使用better-sqlite3并解决NODE_MODULE_VERSION xxx. This version of Node.js requires 2024-11-06
-
Zerotier+Moon+Nginx实现内网穿透搭建网站 2024-08-23
花生壳绑定ubuntu服务器?