Upload file using Guzzle 6 to API endpoint

前端 未结 2 1391
借酒劲吻你
借酒劲吻你 2020-12-05 17:58

I am able to upload a file to an API endpoint using Postman.

I am trying to translate that into uploading a file from a form, uploading it using Laravel and posting

相关标签:
2条回答
  • 2020-12-05 18:30

    The way you are POSTing data is wrong, hence received data is malformed.

    Guzzle docs:

    The value of multipart is an array of associative arrays, each containing the following key value pairs:

    name: (string, required) the form field name

    contents:(StreamInterface/resource/string, required) The data to use in the form element.

    headers: (array) Optional associative array of custom headers to use with the form element.

    filename: (string) Optional string to send as the filename in the part.

    Using keys out of above list and setting unnecessary headers without separating each field into one array will result in making a bad request.

    $res = $client->request('POST', $this->base_api . $endpoint, [
        'auth'      => [ env('API_USERNAME'), env('API_PASSWORD') ],
        'multipart' => [
            [
                'name'     => 'FileContents',
                'contents' => file_get_contents($path . $name),
                'filename' => $name
            ],
            [
                'name'     => 'FileInfo',
                'contents' => json_encode($fileinfo)
            ]
        ],
    ]);
    
    0 讨论(0)
  • 2020-12-05 18:46
    $body = fopen('/path/to/file', 'r');
    $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
    

    http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=file

    0 讨论(0)
提交回复
热议问题