2015-12-15 91 views
3

我正在修改一個將圖像上傳到imgur的示例。該示例使用捲曲,我正在使用guzzle^6.1。與捲曲的例子是:將cURL轉換爲Guzzle POST

<html> 
    <h3>Form</h3> 
    <form method="post" enctype="multipart/form-data"> 
    <input type="hidden" name="MAX_FILE_SIZE" value="50000" /> 
    Image (< 50kb): <input type="file" name="upload" /><br/> 
    ClientID: <input type="text" name="clientid" /><br/> 
    <input type="submit" value="Upload to Imgur" /> 
    </form> 
</html> 
<?php 

if (empty($_POST['clientid']) || @$_FILES['upload']['error'] !== 0 || @$_FILES['upload']['size'] > 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 "<h3>Image</h3>"; 
printf('<img height="180" src="%s" >', @$reply->data->link); 

echo "<h3>API Debug</h3><pre>"; 
var_dump($reply); 

我嘗試轉換使用下面的代碼狂飲:

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錯誤的請求;我的代碼有什麼問題?

回答

4

第一眼,我看到了兩個問題:

  1. Authorization頭。在您的Guzzle版本中,您使用Authorization: Client-ID作爲標頭名稱$client_id作爲標頭值。這將產生一個(錯誤)的HTTP頭,看起來像這樣:

    Authorization: Client-ID: myclientid 
    

    解決方案:通過你的標題是這樣的:

    "headers" => [ 
        "authorization" => "Client-ID " . $clientId 
    ] 
    
  2. 的請求主體。您的原始基於cURL的版本包含一個帶有image參數的URL查詢編碼主體。該參數包含圖像文件的base64編碼原始內容。在您的Guzzle版本中,由於您使用的是不存在的image選項(請查看Guzzle documentation以獲取所有支持選項的列表),因此您實際上不會發送任何物體。此外,您的原始示例不包含data:image/png;base64,前綴(通常只是瀏覽器的提示)。

    嘗試傳遞參數如下:

    "form_params" => [ 
        "image" => base64_encode(/* image content here */) 
    ]