I have a rest API with multiple file and string with same key.
I was test with python Requests => successful
Sample code:
import requests
url = "http://localhost:5000/api/v1/mms/campaign/create_static"
payload={'SentDate': '23-03-2022 09:15:00',
'Sender': 'Sender',
'Msg': 'MMS test.'}
files=[
('Msg',('image2.jpg',open('image2.jpg','rb'),'image/jpeg')),
('Msg',('image1.jpg',open('image1.jpg','rb'),'image/jpeg')),
('ListPhone',('csv_file.csv',open('csv_file.csv','rb'),'text/csv'))
]
headers = {
'Authorization': 'Basic key=='
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
but main language use for my project is PHP
How to post multiple file and string throw cURL of PHP or another way?
This is sample code generate by Postman for php-cURL:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:5000/api/v1/mms/campaign/create_static',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array(
'SentDate' => '23-03-2022 09:15:00',
'Sender' => 'Sender',
'Msg' => 'MMS test.',
'Msg'=> new CURLFILE('image1.jpg'),
'Msg'=> new CURLFILE('image2.jpg'),
'ListPhone'=> new CURLFILE('csv_file.csv')
),
CURLOPT_HTTPHEADER => array(
'Authorization: Basic key=='
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Sorry my english is not good
Thanks for all!
My Answer:
In PHP cURL, you can post multiple files and strings with the same key by using an array for the CURLOPT_POSTFIELDS option. Here's an example code snippet:
php
$curl = curl_init();
$data = array(
'SentDate' => '23-03-2022 09:15:00',
'Sender' => 'Sender',
'Msg' => 'MMS test.',
'Msg1' => new CURLFILE('image1.jpg'),
'Msg2' => new CURLFILE('image2.jpg'),
'ListPhone' => new CURLFILE('csv_file.csv')
);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:5000/api/v1/mms/campaign/create_static',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
'Authorization: Basic key=='
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>
In this code snippet, I have added 'Msg1' and 'Msg2' keys to differentiate between the two image files being uploaded. This way, you can post multiple files and strings with the same key using PHP cURL.
Rate this post
3 of 5 based on 3890 votesComments