Guzzle: how to send a file and a second text field? - php

I must simulate the sending of a form which has
a file selector
a text input
I'm sending the file using this snippet
$response = $this->getClient()->request(
$method,
$endpoint,
[
'headers' => ['Content-Type' => 'multipart/form-data' ],
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => 'file _name.tiicsti',
'contents' => 'hello my content',
'filename' => 'filename.txt',
]
]
]
)
;
It works.
My question is: how to send a text field in addition to my file?

Resolved !
I am surprise that headers is not needed. Probably Guzzle makes some magic
$response = $this->getClient()->request(
$method,
$endpoint,
'multipart' => [
[
'name' => 'text-field-name',
'contents' => 'text field value'
],
[
'name' => 'file _name.tiicsti',
'contents' => 'hello my content',
'filename' => 'filename.txt',
]
]
]
)
;

Related

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"}'

guzzle, how to force content-type in a multipart/form-data

I'm new with Guzzle and I'm trying to make a REST request to sign PDF file. The provider says :
you need to use BASIC authentication
the request must be a POST request
the mimetype should be multipart/form-data
the file sent must be application/octet-stream and its name should be "file"
the data sent must be application/json and its name should be "data"
The system returns a response which contains the signed PDF file and type is application/octet-stream
This is the code I tested with Guzzle, but the provider says that the type mime sent in application/pdf. How can I "force" the mimetype for the PDF file ?
$client = new Client([
'auth' => ['login', 'password'],
'debug' => true,
'curl' => [
CURLOPT_PROXY => '192.168.1.232',
CURLOPT_PROXYPORT => '8080',
CURLOPT_PROXYUSERPWD => 'username:password',
],
]);
$boundary = 'my_custom_boundary';
$multipart = [
[
'name' => 'data',
'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
'Content-Type' => 'application/json'
],
[
'name' => 'file',
'contents' => fopen('documentTest.pdf', 'r'),
'Content-Type' => 'application/octet-stream'
],
];
$params = [
'headers' => [
'Connection' => 'close',
'Content-Type' => 'multipart/form-data; boundary='.$boundary,
],
'body' => new GuzzleHttp\Psr7\MultipartStream($multipart, $boundary),
];
try{
$response = $client->request('POST', 'https://server.com/api/sendDocument', $params);
} catch (RequestException $e) {
echo Psr7\str($e->getRequest());
if ($e->hasResponse()) {
echo Psr7\str($e->getResponse());
}
}
Thank you for your help.
You have to pass the Content-Type in headers
$multipart = [
[
'name' => 'data',
'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
'headers' => [ 'Content-Type' => 'application/json']
],
[
'name' => 'file',
'contents' => fopen('documentTest.pdf', 'r'),
'headers' => [ 'Content-Type' => 'application/octet-stream']
],
];
in Guzzle Documentation say that you can specify headers for every multipart data.
If you not set header Guzzle put a Content-Type for you based on file.

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'
]
]
]);

Sendgrid sending mail with attachment using web api v3

I'm new to using sendgrid web api v3. link here
Right now. It was easy to send a plain html using there api 'POST https://api.sendgrid.com/v3/mail/send' but I have this instance where we will attach a file (csv/xls,pdf) and I can't seem to get it right.
Here is my code below:
My function postSendMail
public function postSendMail($data = [])
{
if ( ! arrayHasValue($data) ) $this->error(__METHOD__, "Data is empty.");
$request = Curl::to( $this->apiUrl.'mail/send' )
->withHeader('Authorization: Bearer '. $this->apiKey)
->withData( $data )
->asJson(true)
->enableDebug(storage_path('logs/laravel-'.php_sapi_name().'.log'))
->post();
return $request;
}
//my instance
$sendgrid = new Sendgrid;
$data = [
'personalizations' => [
[
'to' => [
[ 'email' => 'myemail#gmail.com' ]
],
'subject' => 'Hello, World!'
]
],
'from' => [
'email' => 'myemail#gmail.com',
'name' => 'my_site'
],
'content' => [
[
'type' => 'text',
'value' => 'Hello, World!'
]
],
'track_settings' => [
[
'click_tracking' => true,
'open_tracking' => true
]
],
'attachments' => [
[
'content' => base64_encode(config('global.UPLOAD_PATH') . '/my_file.pdf'),
'type' => 'application/pdf',
'filename' => 'my_file.pdf',
'disposition' => 'attachment'
]
]
];
$lists = $sendgrid->postSendMail($data);
Mail was successfully sent but when I view the attached file, it was corrupted/unable to view. Can anyone help me? :(
Please help.
The problem is that you are not reading the file into an object and then encoding that object; you're encoding a string containing the file path.
'content' => base64_encode(config('global.UPLOAD_PATH') . '/my_file.pdf')
All of your attachments in the tests are probably the same size, and smaller than the actual file as a result.
Try something like:
$imagedata = file_get_contents(config('global.UPLOAD_PATH') . '/my_file.pdf');
$base64 = base64_encode($imagedata);
Coming to main point you need to get file content either by curl request or by file_get_content then encode the that content into attachments->content parameter, Please check following code which works for me:
'attachments' => [
[
'content' => base64_encode(file_get_contents(config('global.UPLOAD_PATH') . '/my_file.pdf')),
'type' => 'application/pdf',
'filename' => 'my_file.pdf',
'disposition' => 'attachment'
]
]

Guzzle 6 send multipart data

I'd like to add some data to a Guzzle Http Request. There are file name, file content and header with authorization key.
$this->request = $this->client->request('POST', 'url', [
'multipart' => [
'name' => 'image_file',
'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
'headers' =>
['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
]]);
but I get error
Catchable Fatal Error: Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string
given, called in vendor\guzzlehttp\psr7\src\MultipartStream.php on line 70 and defined in vendor\guzzlehttp\psr7\src\MultipartStream.php line 79
In Guzzle 6 documentation is something like this: http://docs.guzzlephp.org/en/latest/request-options.html#multipart
Who knows where I made a mistake?
Here is the solution. Header with access token should be outside multipart section.
$this->request = $this->client->request('POST', 'request_url', [
'headers' => [
'Authorization' => 'Bearer access_token'
],
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => 'image_file',
'contents' => fopen('image_file_url', 'r')
]
]
]);
As per the docs, "The value of multipart is an array of associative arrays", so you need to nest one level deeper:
$this->request = $this->client->request('POST', 'url', [
'multipart' => [
[
'name' => 'image_file',
'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
'headers' => ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
]
]
]);
try this
works for me
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;
$this->client = new Client([
'base_uri' => 'https://baseurl'
]);
$body = Utils::tryFopen($tempPath . $fileName, 'r');
$res = $this->client->request(
'POST',
'url',
[
'headers' => [
...
],
'body' => $body
]
);

Categories