問題描述
đăng dữ liệu json với php curl cho đa phần / dữ liệu biểu mẫu để tải lên tệp nếu cakephp 2 (post json data with php curl for multipart/form‑data for file upload vía cakephp 2)
i want to post json data with php curl for a multipart/form‑data with a file upload field. i tried this in cakephp 2 in a action:
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 is the equivalent for the file upload field in a form. subject and body are the equivalent for text fields in a form. i miss something may be in the data array or in the Content‑Type but can't find the problem.
thanks for any help, regards, martin
參考解法
方法 1:
From http://dtbaker.net/web‑development/uploading‑a‑file‑using‑curl‑in‑php/: notice the @ infront of the file path, this is the magic part.
<?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);
?>
Seems you were missing the magic part.
You may also switch from cURL to CakePHP's HttpSocket, but that's just personal prefrence. http://book.cakephp.org/2.0/en/core‑utility‑libraries/httpsocket.html
(by mart、johhniedoe)