Sending file to API with http client

Viewed 4767

I'm working on sending a file to an api endpoint that is giving me the following curl example to post.

curl -X POST -H "Authorization: ACCESS_TOKEN" -H "Content-Type: multipart/form-data" -F "file=@submission.zip" api_url

This is the code I'm using - prior to this I'm getting a successful authentication response but a 500 response from this.

$file = fopen('C:\\Users\\username\\Desktop\\api\\' . $fileName, 'r');

        return $this->client->request(
            'POST',
            'api_url', [
                'headers'=>[
                    'Authorization'=>$accessToken,
                    'Content-Type'=> 'multipart/form-data'
                ],
                'body'=>[
                    'file'=> $file
                ]
            ]
        );

I'm not sure what else I'm missing here. Any suggestions are appreciated.

1 Answers

If you want to send the only file, then try to change your code to

'body' => fopen('C:\\Users\\username\\Desktop\\api\\' . $fileName, 'r')

If you want to send the file with some fields, you can try something like this

use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;

$data = [
    'data' => 'some data',
    'file' => DataPart::fromPath('/path/to/file'),
];

$formData = new FormDataPart($data);
$headers = $formData->getPreparedHeaders()->toArray();
$headers['Authorization'] = $accessToken;
$headers['Content-Type'] = 'multipart/form-data';
$client->request('POST', 'api_url', [
    'headers' => $headers,
    'body' => $formData->bodyToIterable(),
]);
Related