2016-05-13 74 views
0

我想向Guzzle Http請求添加一些數據。有文件名,文件內容和帶有授權密鑰的標題。Guzzle 6發送多部分數據

$this->request = $this->client->request('POST', 'url', [ 
    'multipart' => [ 
     'name' => 'image_file', 
     'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'), 
     'headers' => 
      ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw'] 
      ]]); 

,但我得到的錯誤

Catchable Fatal Error: Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string given, called in vendor\guzzlehttp\psr7\src\MultipartStream.php on line 70 and defined in vendor\guzzlehttp\psr7\src\MultipartStream.php line 79

在狂飲6文檔是這樣的:http://docs.guzzlephp.org/en/latest/request-options.html#multipart

誰知道我犯了一個錯誤?

+0

有一些例子在這裏:創建與密碼交付式驗證一個symfony的OAuth2用戶API客戶端(http://www.inanzzz.com/index.php/post/l4zx/creating-a-symfony -oauth2-api-client-that-authenticates-with-password-grant-type)和[從另一個應用程序中使用帶有Guzzle客戶端的symfony API](http://www.inanzzz.com/index.php/post/u0xf/使用symfony-api-with-guzzle-client-from-another-application) – BentCoder

+0

但是,這些教程都是以前的Guzzle版本。我正在使用最新版本。 –

+0

第一個鏈接使用guzzle 6 – BentCoder

回答

4
這裏

是解決方案。帶訪問令牌的標題應該位於多部分外部。

$this->request = $this->client->request('POST', 'request_url', [ 
      'headers' => [ 
       'Authorization' => 'Bearer access_token' 
      ], 
      'multipart' => [ 
       [ 
        'Content-type' => 'multipart/form-data', 
        'name' => 'image_file', 
        'contents' => fopen('image_file_url', 'r') 
       ] 
      ] 
     ]); 
1

按照該文檔,「多部分的值是關聯數組的陣列」,所以就需要巢更深一層:

$this->request = $this->client->request('POST', 'url', [ 
    'multipart' => [ 
     [ 
      'name' => 'image_file', 
      'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'), 
      'headers' => ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw'] 
     ] 
    ] 
]); 
+0

我格式化代碼,但得到相同的錯誤。 –

+0

@PrzemekGawłowski我並不是說你只需要以不同的方式對代碼進行格式化,就需要給出multipart選項「一組關聯數組」。在你的代碼中,你只是給它一個單一的關聯數組。像我的例子一樣,在它周圍包裹一些額外的方括號。 – iainn

+0

你說得對,我的不好。所以現在我得到了這個錯誤信息:-( '可捕捉的致命錯誤:類GuzzleHttp \ Psr7 \ Response的對象無法轉換爲字符串在features \ bootstrap \ FeatureContext.php行246' –