Upload file using Guzzle 6 to API endpoint

旧巷老猫 提交于 2019-11-29 01:12:24

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!