2017-10-12 93 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'] 
     ], 
    ], 
]);