PHP cURL上传无法正常工作

时间:2016-11-03 14:09:16

标签: php rest api curl

我正在尝试使用PHP cURL将URL中的文件POST发送到另一台服务器并收到错误:

  

处理您的请求时出错。

这是我的代码:

$url = 'http://www.example.com/api/uploads';
$fields = array('id' => $apikey,'token' => $token ,'myFile' => array(urlencode(base64_encode(file_get_contents("http://www.pdf995.com/samples/pdf.pdf")))));
$data_json = json_encode($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data', 'cache-control: max-age'));
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

1 个答案:

答案 0 :(得分:1)

如果您想上传文件,字段应该是这样的。

// file from your local directory
$fields = array('id' => $apikey,'token' => $token ,'myFile' => "@/samples/pdf.pdf");

帖子字段应为:

curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);

删除选项CURLOPT_HTTPHEADER