5

我正在尝试使用以下代码使用 Telegram Bot API 上传图片

if(file_exists($_FILES['fileToUpload']['tmp_name'])){
        $new = fopen($_FILES['fileToUpload']['tmp_name'], "rb");
        $contents = fread($new, $_FILES['fileToUpload']['size']);
        fclose($new);
        $client = new Client();
        $response = $client->post("https://api.telegram.org/botMyApiKey/sendPhoto", [
            'body'    => ['chat_id' => '11111111', 'photo' => $contents]
        ]);
        var_dump($response);
}else{
        echo("No File");
}

我越来越Nginx 502 Bad Gateway。我使用正确的方法吗?我在获取getMe使用 API 方面没有任何问题。

PS 我使用 Guzzle 5.3.0 来实现 php 兼容性。

4

2 回答 2

1

尝试将其作为多部分帖子进行。

$client->post(
    'https://api.telegram.org/botMyApiKey/sendPhoto', 
    array(
        'multipart' => array(
            array(
                'name'     => 'chat_id',
                'contents' => '1111111'
            ),
            array(
                'name'     => 'photo',
                'contents' => $contents
            )
        )
    )
);

Guzzle 文档参考

对于 Guzzle 5.3

use GuzzleHttp\Client;

$client = new Client(['defaults' => [
    'verify' => false
]]);

$response = $client->post('https://api.telegram.org/bot[token]/sendPhoto', [
    'body' => [
        'chat_id' => 'xxxxx',
        'photo' => fopen(__DIR__ . '/test.jpg', 'r')
    ]
]);

var_dump($response);

注意:您必须将文件句柄传递给“照片”属性,而不是文件的内容。

于 2015-07-04T14:03:53.190 回答
1

我终于找到了解决方案。为其他人粘贴我的解决方案。

move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__."/temp/".$_FILES['photo']['name']); //Important for Form Upload
$client = new Client();
$request = $client->createRequest('POST', 'https://api.telegram.org/botMyApiKey/sendPhoto');
$postBody = $request->getBody();
$postBody->setField('chat_id', '11111111');
$postBody->addFile(new PostFile('photo', fopen(__DIR__."/temp/".$_FILES['photo']['name'], "r") ));
try{
     $response = $client->send($request);
     var_dump($response);
}catch(\Exception $e){
     echo('<br><strong>'.$e->getMessage().'</strong>');
}

我很困惑为什么这适用于这种 Guzzle 方法而不是另一种方法。我怀疑 Guzzle 没有使用第一种方法设置正确的标题类型。

于 2015-07-04T19:13:28.070 回答