简体   繁体   中英

How to post files using cURL

I am using cURL for the first time. I have to send one image file and one audio file posted by the user.

My cURL code is working, but instead of an image file and an audio file my code is sending a .tmp file.

I googled it, but in every example I found they have used realpath of file directly.

I tried to find real path of the file, but I didn't find any solution. Here is my code block in which I am collecting all data in an array to pass it to cURL:

$name = $_POST['name'];

$image = $_POST['image']['name'];
$imagetmp = $_POST['image']['tmp_name'];
$imagesize = $_POST['image']['size'];
$imagepath = '@'.$imagetmp;

$audio = $_POST['audio']['name'];
$audiotmp = $_POST['audio']['tmp_name'];
$audiosize = $_POST['audio']['size'];
$audiopath = '@'.$audiotmp;

$data = array("name" => $name, "image"=> $imagepath, "audio" => $audiopath); //array to sned data using cURL

//my cURL code to post data

Where am I doing wrong? How to send files using cURL?

This is what I used to post file data:

$filedata = file_get_contents('file_location/filename.jpg');    
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $filedata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/octet-stream'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$return = curl_exec($ch);
curl_close($ch);

You can use file=@path with curl

curl -kiSs -X POST https://<domain>/path/to/api/files/ \
-F "param1=param2" \
-F "file=@/path/to/test.xlsx"  \
-H "Authorization":"bearer eyJhbGciOiJIUzI1NiIsIn"

File successfully uploaded (test.xlsx!) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM