John Kornick
John Kornick

Reputation: 295

POST multipart/form-data with Guzzle 4

I'm using Guzzle 4 and I want to POST files with multipart/form-data. I'm not sure which is the right way to do this.

I've tried:

$client = new GuzzleHttp\Client();

$request = $client->createRequest('POST', 'https://127.0.0.1/1/files/', ['json' => ['id' => 'dc51bfe4-92af-483d-80c4-f2da4cafa723'], 'cookies' => true]);

$request->getBody()->addFile(new PostFile('a.pdf', fopen('a.pdf', 'rb')));
$response = $this->client->send($request);

I'm getting this error:

Fatal error: Call to undefined method GuzzleHttp\Stream\Stream::addFile()

The same happens if I replace addFile with addPostFile.

Any ideas?

Upvotes: 0

Views: 2674

Answers (1)

Maury
Maury

Reputation: 620

Never used Guzzle, but I tried this code out and was able to fix it by replacing

$request = $client->createRequest('POST', 'https://127.0.0.1/1/files/', ['json' => ['id' => 'dc51bfe4-92af-483d-80c4-f2da4cafa723'], 'cookies' => true]);

with this

$request = $client->createRequest('POST', 'https://127.0.0.1/1/files/', ['cookies' => true]);

You can probably pass the json data after the createRequest. You should check the Guzzle documentation for that.

Also, you seem to be using both $client and $this->client. I think you probably should just stick to one of the two.

Upvotes: 1

Related Questions