使用Guzzle上传文件

时间:2017-10-12 13:10:19

标签: php laravel curl

我有一个表格可以上传视频并发送到远程目的地。我有一个cURL请求,我希望使用Guzzle将其“翻译”为PHP。

到目前为止,我有这个:

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:

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

所以当我上传视频时,我想替换这个硬编码的

C:\用户\ PROD \下载\ 617103.mp4

当我运行时,我收到错误:

  

客户端错误:POST http://mydomain.de:8080/spots导致400 Bad Request响应:请求正文无效:期望表单值'body`'

     

客户端错误:POST http://mydomain.de/spots导致400 Bad Request响应:       请求正文无效:期望表单值'body'

2 个答案:

答案 0 :(得分:4)

我会查看Guzzle的multipart请求选项。我看到两个问题:

  1. 需要对JSON数据进行字符串化并使用您在curl请求中使用的相同名称进行传递(它的名称为body)。
  2. curl请求中的type映射到标头Content-Type。来自$ man curl

      

    您还可以使用'type ='来告诉curl要使用的Content-Type。

  3. 尝试类似:

    $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']
            ],
        ],
    ]);
    

答案 1 :(得分:0)

  • 在使用 multipart 选项时,请确保您没有传递 content-type => application/json :)
  • 如果您想同时发布表单字段和上传文件,只需使用此 multipart 选项。它是一个数组数组,其中 name 是表单字段名称,它的值是发布的表单值。一个例子:
'multipart' => [
                [
                    'name' => 'attachments[]', // could also be `file` array
                    'contents' => $attachment->getContent(),
                    'filename' => 'dummy.png',
                ],
                [
                    'name' => 'username',
                    'contents' => $username
                ]
            ]
相关问题