简体   繁体   English

如何使用 cURL 发布文件

[英]How to post files using cURL

I am using cURL for the first time.我第一次使用 cURL。 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.我的 cURL 代码正在运行,但我的代码发送的是 .tmp 文件,而不是图像文件和音频文件。

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:这是我的代码块,我在其中收集数组中的所有数据以将其传递给 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?如何使用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您可以将 file=@path 与 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!) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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