2013-04-04 59 views
0

我想發佈JSON數據與PHP捲曲的多部分/表單數據與文件上傳領域。 i的一個動作嘗試這樣CakePHP中2:張貼JSON數據與PHP捲曲的多部分/表單數據的文件上傳víacakephp 2

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); 


} 

文件名是用於在形式與該文件上傳字段的等價物。 主體和主體相當於表單中的文本字段。 我錯過了可能在數據數組或Content-Type中的東西,但無法找到問題。

任何幫助的感謝,問候,馬丁

回答

0

http://dtbaker.net/web-development/uploading-a-file-using-curl-in-php/通知文件路徑的@盈,這是魔法的一部分。

<?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,但這只是個人的偏好。 http://book.cakephp.org/2.0/en/core-utility-libraries/httpsocket.html

+0

謝謝,這就是它。我也切換到CakePHP的HttpSocket。 – mart 2013-05-05 21:37:29

+0

你可以顯示相當於curl的HttpSocket來「放」json數據嗎? – Divyanshu 2013-10-15 04:31:00

+0

@Divyanshu http://book.cakephp.org/2.0/en/core-utility-libraries/httpsocket.html#HttpSocket::put – johhniedoe 2013-10-17 10:36:14

相關問題