使用 Guzzle 将照片上传到电报 API

Upload a photo to telegram API using Guzzle

我想发送照片(或其他类型的文件,如视频或文档)。
如何将照片(从本地)上传到电报?

$client->request('POST', 'sendPhoto', [
    'query' => [
        'chat_id'=> 'xxxxx',
        'photo'=> fopen('img.png', 'r')
    ]
]);

但这对我不起作用。
如何从我的本地系统发送照片到电报?

如果您想要 post 文件,您需要使用 multipart

$client->request('POST', 'sendPhoto', [
  'multipart' => [
    [ 'name' => 'chat_id', 'contents' => 'xxxxx'],
    [
      'name' => 'photo',
      'contents' => fopen('img.png', 'r')
    ]
  ]
]);

如果您有很多参数,您可以使用映射关联数组的辅助函数:

function toMultiPart(array $arr) {
  $result = [];
  array_walk($arr, function($value, $key) use(&$result) {
    $result[] = ['name' => $key, 'contents' => $value];
  });
  return $result;
}

$client->request('POST', 'sendPhoto', [
  'multipart' => toMultiPart([
    'chat_id'=> 'xxxxx',
    'photo'=> fopen('img.png', 'r')
  ])
});