Send Multipart Form from PHP with Guzzle - php

I'm trying to create a multipart form for upload file in my API.
According the docs of guzzle :
\\$data = picture of form
\\$uri = Endpoint in my API
$this->client->post($uri, [
'multipart' => [
[
'name' => 'picture',
'contents' => file_get_contents($data),
]
],
'headers' => $headers
]);
When I'm using Insomnia or Postman :
I'm not understand why it not working in Guzzle.

$file = new File($data->getPathname());
$tmp_picture_path = Storage::putFile("temp_dir", $file);
$tmp_picture = Storage::readStream($tmp_picture_path);
$response = $this->client->post(
$uri,
[
'multipart' => [
[
'name' => 'picture',
'contents' => $tmp_picture,
'filename' => "avatar." . $data->getClientOriginalExtension()
]
],
'headers' => $headers
]
);
Storage::delete($tmp_picture_path);
Just save locally the file and read the stream dor send it properly.

Related

Upload image to facebook using graph api in PHP

I'm trying to upload an image to facebook using graph api. I want to submit the image as a file instead of providing a URL which is another option. I'm using PHP Laravel and guzzle to achieve this. Unfortunately when I upload the file I'm getting an error which would seem to indicate that the image is not recognised.
This is the documentation I am using
https://developers.facebook.com/docs/graph-api/reference/page/photos/#publish
This is my error message
message: "Client error: `POST https://graph.facebook.com/v12.0/99999999999/photos` resulted in a `400 Bad Request` response:\n{\"error\":{\"message\":\"(#324) Requires upload file\",\"type\":\"OAuthException\",\"code\":324,\"fbtrace_id\":\"ACxilINTWYdb3wGOXfGg7 (truncated...)\n"
Here is my code
public function media(Request $request)
{
$facebookPageConnection = FacebookPageConnection::find(2);
$file = $request->file('file');
$client = new Client();
$body = $client->post("https://graph.facebook.com/v12.0/$facebookPageConnection->facebook_page_id/photos", [
'multipart' => [
[
'name' => 'message',
'contents' => 'test post'
],
[
'name' => 'source',
'contents' => base64_encode(file_get_contents($file))
],
[
'name' => 'access_token',
'contents' => $facebookPageConnection->access_token
]
]
])->getBody();
return json_decode($body);
}
My mistake was to use
file_get_contents
and
base64_encode
Instead to get it to work I needed to use fopen
$body = $client->post("https://graph.facebook.com/v12.0/$facebookPageConnection->facebook_page_id/photos", [
'multipart' => [
[
'name' => 'message',
'contents' => 'test post'
],
[
'name' => 'source',
'contents' => fopen($file, 'rb')
],
[
'name' => 'access_token',
'contents' => $facebookPageConnection->access_token
]
]
])->getBody();

Issue converting from cURL to Guzzle 6 with JSON and XML file

I am having a hard time converting cURL to Guzzle6. I'm want to send a name and reference UUID via JSON AND the contents of an XML file to process to a REST endpoint.
cURL
curl -H 'Expect:' -F
'request={"name":"test", "reference":"870e0320-021e-4c67-9169-d4b2c7e5b9c9"}'
-F 'file=#sample.xml' http://ec2-48-88-173-9.us-east-1.compute.amazonaws.com:8180/rs/process
Guzzle
$client = new Client(['debug' => true]);
$request = $client->request('POST',
'http://ec2-48-88-173-9.us-east-1.compute.amazonaws.com:8180/rs/process', [
'multipart' => [
[
'name' => 'data',
'contents' => "{'name':'test','reference':870e0320-021e-4c67-9169-d4b2c7e5b9c9}",
'headers' => ['Content-Type' => 'application/json']
],
[
'name' => 'file',
'contents' => fopen('sample.xml', 'r'),
'headers' => ['Content-Type' => 'text/xml']
],
]
]
);
$response = $request->getBody()->getContents();
Also, I'm not sure what the 'name' fields should be ('name' => 'data'), etc.
This is the Guzzle equivalent of your curl command:
$client = new Client(['debug' => true]);
$request = $client->request('POST',
'http://ec2-48-88-173-9.us-east-1.compute.amazonaws.com:8180/rs/process', [
'multipart' => [
[
'name' => 'request',
'contents' => "{'name':'test','reference':870e0320-021e-4c67-9169-d4b2c7e5b9c9}",
],
[
'name' => 'file',
'contents' => fopen('sample.xml', 'r'),
],
]
]
);
$response = $request->getBody()->getContents();
For the file Guzzle will specify the appropriate content type, as curl does. Name for the first part is request — from -F
'request={"name":"test", "reference":"870e0320-021e-4c67-9169-d4b2c7e5b9c9"}'

Post data and file using Guzzle - PHP & Laravel

I am using guzzle 6.3 to post a file along with some data to my api built on laravel 5.5. When i post the data, i am not able to get the data sent to the api except the file posted.
Client Side
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->request('POST',$url, [
'multipart' => [
[
'name' => 'body',
'contents' => json_encode(['documentation' => 'First Doc', 'recipient' => ['78011951231']]),
'headers' => ['Content-Type' => 'application/json']
],
[
'name' => 'file',
'contents' => fopen('/path/public/media/aaaah.wav', 'r'),
'headers' => ['Content-Type' => 'audio/wav']
],
],
]);
echo($response->getBody()->getContents());
API Controller
if (($Key)) {
return response()->json([
'status' => 'success',
'documenation' => $request->get('documentation'),
'recipient' => $request->get('recipient'),
'file' =>$request->get('file'),
'media'=>$request->hasFile('file')
]);
}
Response
{"status":"error","documentation":null,,"recipient":null,"file":null,"media":true}
Why am i getting NULL returned for the data that i am posting? Could it be because of the file that i am posting ?

Upload image file using slack API files.upload method

The following code seems to work, but the Slack API saves the file a plain text.
protected function upload($file)
{
$client = $this->guzzle;
if (!$token) {
$token = env('SLACK_TOKEN');
}
$response = $client->request('POST', env('SLACK_API') . "/files.upload?token=$token", [
'form_params' => [
'name' => $file->getFilename(),
'content' => File::get($file->getRealPath()),
'filename' => $file->getFilename(),
'filetype' => 'image',
'channels' => "#_test",
]
]);
return json_decode((string)$response->getBody());
}
When I use the guzzle multipart post, I get the error: 'no_file_data' I feel like I am missing something.
Is there a way to upload images or non-text files using the files.upload method in the Slack API?
Almost as soon as I posted this question, I realized that I was formatting the array incorrectly on the multipart post in guzzle.
This seems to work:
$response = $this->guzzle->post(env('SLACK_API') . "/files.upload?token=$token",
['multipart' =>
[
[
'name' => 'filename',
'contents' => $file->getClientOriginalName()
],
[
'name' => 'file',
'contents' => fopen($file,'r')
],
[
'name' => 'channels',
'contents' => '#_test'
]
]
]);

How do I make this POST request with Guzzle6

My working Guzzle5 code looks roughly as follows:
$guzzle = new \GuzzleHttp\Client();
$request = $guzzle->createRequest('POST', $url);
$request->setHeader('Authorization', 'Bearer ' . $token);
$postBody = $request->getBody();
$postBody->setField('name', 'content');//several times
if (check for file) {
$postBody->addFile(new \GuzzleHttp\Post\PostFile('name', fopen(...));
}
$response = $guzzle->send($request);
What with setting a header and maybe adding a file, I’m not sure how to do this with Guzzle6.
Here an example from the official documentation how can you set headers and adding file into your POST request with Guzzle 6:
$client = new \GuzzleHttp\Client();
$client->post('/post', [
'multipart' => [
[
'name' => 'foo',
'contents' => 'data',
'headers' => ['X-Baz' => 'bar']
],
[
'name' => 'baz',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'qux',
'contents' => fopen('/path/to/file', 'r'),
'filename' => 'custom_filename.txt'
],
]
]);
The multipart option sets the body of the request to a multipart/form-data form, if you don't need to work with files you can just use form_params instead of multipart option.
Any headers you can easy set with help headers option.
Additional info you can find here Guzzle Upgrade Guide (5.0 to 6.0)
Here is some code copied from one of my projects:
$client = new GuzzleHttp\Client();
$url = 'someurl.com/api';
$body = json_encode([
'variable1' => 'this',
'variable2' => 'that'
]);
$response = $client->post($url, [
'headers' => [
'header_variable1' => 'foo',
'header_variable2' => 'bar'
],
'json' => true,
'timeout' => 3,
'body' => $body
]);
$data = $response->json();

Categories