2017-10-12 133 views
2

我有一個表單,可以將視頻上傳併發送到遠程目的地。我有一個cURL請求,我想用Guzzle'翻譯'到PHP。使用Guzzle上傳文件

到目前爲止,我有這樣的:

public function upload(Request $request) 
    { 
     $file  = $request->file('file'); 
     $fileName = $file->getClientOriginalName(); 
     $realPath = $file->getRealPath(); 

     $client = new Client(); 
     $response = $client->request('POST', 'http://mydomain.de:8080/spots', [ 
      'multipart' => [ 
       [ 
        'name'  => 'spotid', 
        'country' => 'DE', 
        'contents' => file_get_contents($realPath), 
       ], 
       [ 
        'type' => 'video/mp4', 
       ], 
      ], 
     ]); 

     dd($response); 

    } 

這是捲曲我用,想轉換爲PHP:

curl -X POST -F 'body={"name":"Test","country":"Deutschland"};type=application/json' -F '[email protected]:\Users\PROD\Downloads\617103.mp4;type= video/mp4 ' http://mydomain.de:8080/spots 

所以,當我上傳的視頻,我要取代這個硬編碼

C:\ Users \ PROD \ Downloads \ 617103.mp4

當我運行它,我得到一個錯誤:

Client error: POST http://mydomain.de:8080/spots resulted in a 400 Bad Request response: request body invalid: expecting form value 'body`'

Client error: POST http://mydomain.de/spots resulted in a 400 Bad Request response: request body invalid: expecting form value 'body'

回答

2

我會檢討狂飲的multipart請求選項。我看到兩個問題:

  1. 的JSON數據需要字符串化,並與(它是容易混淆的命名body)您使用的是捲曲請求的同一名稱傳遞。
  2. 捲曲請求中的type映射到標頭Content-Type。從$ man curl

    You can also tell curl what Content-Type to use by using 'type='.

試着這麼做:

$response = $client->request('POST', 'http://mydomain.de:8080/spots', [ 
    'multipart' => [ 
     [ 
      'name'  => 'body', 
      'contents' => json_encode(['name' => 'Test', 'country' => 'Deutschland']), 
      'headers' => ['Content-Type' => 'application/json'] 
     ], 
     [ 
      'name'  => 'file', 
      'contents' => fopen('617103.mp4', 'r'), 
      'headers' => ['Content-Type' => 'video/mp4'] 
     ], 
    ], 
]);