发布json数据与php curl for multipart / form-data for fileuploadvíakquephp2

我想用php curl发布带有文件上传字段的multipart / form-data的json数据 . 我在cakephp 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); 


}

fileName是表单中文件上载字段的等效项 . 主题和正文相当于表单中的文本字段 . 我想念的东西可能在数据数组或Content-Type中但无法找到问题 .

感谢任何帮助,问候,马丁

回答(1)

2 years ago

来自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);
?>

似乎你错过了神奇的部分 .

您也可以从cURL切换到CakePHP 's HttpSocket, but that'只是个人偏好 . http://book.cakephp.org/2.0/en/core-utility-libraries/httpsocket.html