使用php curl发布json数据,用于文件上传的多部分/表单数据ví;cakephp2
我想用php curl发布json数据,以获得带有文件上载字段的多部分/表单数据。 我在cakephp 2中尝试了以下操作:使用php curl发布json数据,用于文件上传的多部分/表单数据ví;cakephp2,json,rest,cakephp,curl,multipartform-data,Json,Rest,Cakephp,Curl,Multipartform Data,我想用php curl发布json数据,以获得带有文件上载字段的多部分/表单数据。 我在cakephp 2中尝试了以下操作: public function json_post(){ $this->autoRender = false; debug('json post test'); $data = array('Post' => array( 'subject' => 'test subject content',
public function json_post(){
$this->autoRender = false;
debug('json post test');
$data = array('Post' => array(
'subject' => 'test subject content',
'body' => 'test body content'
'fileName' => '/Users/mar/Pictures/cow_wall_90.jpg'
));
$data_string = json_encode($data);
$ch = curl_init('http://www.mydomain.com/posts/phone_upload.json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//'Content-Type: multipart/form-data',
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
debug($result);
}
fileName是表单中文件上载字段的等效项。
对于表单中的文本字段,主题和正文是等效的。
我遗漏了数据数组或内容类型中的某些内容,但找不到问题所在
感谢您的帮助和问候,martin来自:
注意文件路径的@前面,这是神奇的部分。
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"@/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
?>
看来你错过了神奇的部分
您也可以从cURL切换到CakePHP的HttpSocket,但这只是个人偏好。
谢谢,就这样。我还切换到了CakePHP的HttpSocket。您能将HttpSocket等效于curl来“放置”json数据吗?@Divyanshu