PHP:开发文件上传到API的CURL请求时遇到问题
在过去几天中,我在php中开发了一个CURL请求,将文件数据发布到API中,遇到了这个问题 这是CURL请求PHP:开发文件上传到API的CURL请求时遇到问题,php,api,curl,file-upload,google-streetview-publish,Php,Api,Curl,File Upload,Google Streetview Publish,在过去几天中,我在php中开发了一个CURL请求,将文件数据发布到API中,遇到了这个问题 这是CURL请求 $ curl --request POST \ --url 'UPLOAD_URL' \ --upload-file 'PATH_TO_FILE' \ --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' 对于PATH_TO_文件,我尝试了通过web发布的每一种方法,也尝试了stackoverflow 这是我的PH
$ curl --request POST \
--url 'UPLOAD_URL' \
--upload-file 'PATH_TO_FILE' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
对于PATH_TO_文件,我尝试了通过web发布的每一种方法,也尝试了stackoverflow
这是我的PHP代码
<?php
header('Content-Type: application/json');
$sheader = array('Authorization: Bearer '.$_SESSION['access_token']);
$filename = $_FILES['upload-file']['name'];
$filedata = $_FILES['upload-file']['tmp_name'];
$filesize = $_FILES['upload-file']['size'];
$filetype = $_FILES['upload-file']['type'];
if($filename != '')
{
$ch = curl_init();
$cFile = new CURLFile(realpath($filename), $filetype, 'harish.jpg');
//$cFile = '@'. realpath($filename);
$data = array('upload-file' => $cFile);
curl_setopt($ch, CURLOPT_POSTFIELDS, $cFile);
//curl_setopt($ch, CURLOPT_POSTFIELDS, realpath($filename));
curl_setopt($ch, CURLOPT_URL, $_POST['upload_url']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $sheader);
curl_exec($ch);
echo json_encode($ch);
//echo json_encode(array('filename'=>$filename, 'temp_path'=>$filedata, 'basepath'=>realpath($filename)));
} else {
echo 'There is no file selected';
}
方法2(对于php>5.5)
或
以上这些都不适合我。我在CURLFile中也使用了realpath($filename)来获取文件的绝对路径,但遗憾的是,这也不起作用。我承认这有点含糊不清,但第一个构造函数参数,$name
,实际上是要发送的实际文件的物理路径,而不是“友好”名称(在可选的第三个参数中,$postname
)。您应该注意,这是有问题的,因为您从未告诉Curl有关$\u文件['upload-file']['tmp\u name']
-它无法知道您要发送的文件
因此:
由于跳过了错误检查,因此不会通知您。您不会检查任何函数的返回值,也不会调用代码中的任何地方
还有一个错误是,您通过以下方式传递CURLFile
实例:
curl_setopt($ch, CURLOPT_POSTFIELDS, $cFile);
正确的语法应该如下所示:
curl_setopt($ch, CURLOPT_POSTFIELDS, ['give_a_nice_post_name_here' => $cFile]);
你试过data binary选项吗?@UmashankarDas我想是的,我也试过data binary。但是如果你建议代码,我可以再试一次。是的,我以前试过,但没有用@UmashankarDas。你是不是因为不知道你的PHP版本而尝试这两种方法?如果你调用
phpi,你可以很容易地确定它nfo()
函数。很抱歉,我没有在这里提到错误调试代码。如果(curl\u errno($ch)){$msg=curl\u error($ch);$return=array('errmsg'=>$msg);echo json\u encode($return);},我的代码中就有这个代码我不擅长阅读注释中的代码,但我想这是好的。Curl有时对错误的信息不是很丰富。我编辑了我的答案。是的,我也通过了这个参数。请参阅我的问题$data=array('upload-file'=>$cFile);我也用它进行了测试:Curl\u setopt($ch,CURLOPT\u POSTFIELDS,$data);
curl_file_create($filedata, 'image/jpeg', $filename);
$filename = $_FILES['upload-file']['name'];
$filedata = $_FILES['upload-file']['tmp_name'];
$filesize = $_FILES['upload-file']['size'];
$filetype = $_FILES['upload-file']['type'];
$cFile = new CURLFile($filedata, $filetype, 'harish.jpg')
curl_setopt($ch, CURLOPT_POSTFIELDS, $cFile);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['give_a_nice_post_name_here' => $cFile]);