我正在调整一个例子来上传一个图像到imgur.该示例使用curl,我使用guzzle ^ 6.1.卷曲的例子是:
50000) { exit; } $client_id = $_POST['clientid']; $filetype = explode('/',mime_content_type($_FILES['upload']['tmp_name'])); if ($filetype[0] !== 'image') { die('Invalid image type'); } $image = file_get_contents($_FILES['upload']['tmp_name']); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json'); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization: Client-ID ' . $client_id )); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'image' => base64_encode($image) )); $reply = curl_exec($ch); curl_close($ch); $reply = json_decode($reply); echo "Form
"; var_dump($reply);
我尝试使用下一个代码转换为Guzzle:
use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request as gRequest; //....Clases and functions ... $url = "https://api.imgur.com/3/image.json"; $client_id = "miclientid"; $client = new Client([ // Base URI is used with relative requests 'base_uri' => $url, // You can set any number of default request options. 'timeout' => 15.0, ]); $gRequest = new gRequest('POST', 'https://api.imgur.com/3/image.json', [ 'headers' => [ 'Authorization: Client-ID' => $client_id ], 'image' => "data:image/png;base64,iVBORw0K..." ]); $gResponse = $client->send($gRequest, ['timeout' => 2]);
但我收到了400个不好的请求; 我的代码有什么问题?
乍一看,我看到两个问题:
该Authorization
头.在你狂饮版本,您使用Authorization: Client-ID
的标题名称,并$client_id
为标头值.这将生成一个(错误的)HTTP标头,如下所示:
Authorization: Client-ID: myclientid
解决方案:像这样传递你的标题:
"headers" => [ "authorization" => "Client-ID " . $clientId ]
请求正文.您原始的基于cURL的版本包含带有image
参数的URL查询编码主体.该参数包含图像文件的base64编码原始内容.在你的Guzzle版本中,你实际上根本没有发送一个正文,因为你正在使用不存在的image
选项(请查看Guzzle文档以获取所有支持选项的列表).此外,您的原始示例不包含data:image/png;base64,
前缀(通常只是浏览器的提示).
尝试传递参数如下:
"form_params" => [ "image" => base64_encode(/* image content here */) ]