尝试使用Curl将图像发送到API时,我感到非常沮丧。图片来自客户端的 html表单。提交表单后,我检查以确保该文件是图片,并且该图片已按以下方式移至上载文件夹:
$location = "ImageUploads/";
if(isset($_FILES["Image"]["tmp_name"]))
{
$checkImage = getimagesize($_FILES["Image"]["tmp_name"]);
if($checkImage !== false){
$Image = $_FILES['Image']['tmp_name'];
$ImageContent = addslashes(file_get_contents($Image));
$ImagePosted =true;
$ImageRealName = $_FILES['Image']['name'];
if(move_uploaded_file($Image, $location.$ImageRealName))
{
echo 'File Uploaded';
}
}
else{
echo 'Image not submitted';
}
将图像移至上载文件夹后,将启动curl Post,如下所示:
$baseURL ="https://apithatIamusing.com/api/";
$curl = curl_init($baseURL);
$myImage = new CURLFile($location.$_FILES['Image']['name'],$_FILES['Image']['type'],$_FILES['Image']['name']);
此后,我创建一个curl_post_data数组以包含其余的api数据要求:
$curl_post_data = array(
'public_key' => $publicKey,
'private_key' => $privateKey,
'order_type' => 'Image',
'origin_id' => '11111111',
'name' => $FirstName,
'surname' => $LastName,
'photo' => $myImage);
然后我设置将要使用的所有Curtopts:
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_UPLOAD, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
然后我执行并尝试解码json响应:
$imageResult= curl_exec($curl);
if($imageResult ===false)
{
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
$imageJson = json_decode($imageResult, true);
curl_close($curl);
$imageSuccess = $imageJson["success"];
$imageMessage = $imageJson["message"];
$imageSuccess = $imageJson["result"];
echo '<p>imageSuccess:'.$imageSuccess.' </p>';
echo '<p>imageMessage: '.$imageMessage.' </p>';
echo '<p>imageSuccess: '.$imageSuccess.' </p>';
我认为问题可能出在curl创建的$ myImage上,api文档要求“照片”包含以下信息:
filename="t1.png"
Content-Type: image/png
但是,据我了解,curlfile包括名称,内容类型和帖子名称。任何建议或其他使用php进行api调用的方法将不胜感激。