cUrl与json字符串和文件上传

时间:2017-10-26 19:11:32

标签: php json curl watson visual-recognition

如何将以下curl命令“转换”为有效的php curl函数?

curl -X POST 
     -F "images_file=@fruitbowl.jpg" 
     -F parameters=%7B%22classifier_ids%22%3A%5B%22testtype_205919966%22%5D%2C%22threshold%22%3A0%7D  
     'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={key}&version=2016-05-20'"

我似乎做错了,我无法弄清楚问题:

$method = 'POST'
$url = 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=<myApiKey>&version=2016-05-20'
$data = array(
    array(<file-information>),
    array(<json-string>),
)
$header = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen(<json-string>),
                )
        )

public function send($method, $url, $data = null, $header = null)
{
    $curl = curl_init();

    switch ($method) {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data) {
                $postData = $this->renderPostData($data);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
            }
            break;
    }

    if($header) {
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
}

protected function renderPostData($data)
{
    $postData = array();
    foreach ($data as $file) {
        if ($file['isFile']) {
            if(pathinfo($file['path'], PATHINFO_EXTENSION) == 'zip'){
                $postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);
            }
            else {
                $postData[$file['name']] = new \CURLFile($file['path'], 'application/octet-stream', $file['name']);
            }
        } else {
            // this contains the json encoded string
            $postData[$file['name']] = $file['path'];
        }
    }

    return $postData;
}

我尝试了几种变体,现在出现了Watson Visual Recognition API错误:

  

{       “custom_classes”:0,       “图片”: [           {               “错误”:{                   “description”:“图像数据无效。支持的格式为JPG和PNG。”,                   “error_id”:“input_error”               }           }       ]       “images_processed”:1   }

之前:

  

{       “错误”:{           “代码”:400,           “description”:“收到无效的JSON内容。无法解析。”,           “error_id”:“parameter_error”       },       “images_processed”:0   }

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我的问题是这一行:

$postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);

最后一个参数是$ postname。因此,要解决此问题,我必须将此行更改为:

$postData[$file['name']] = new \CURLFile($file['path'], mime_content_type($file['path']), basename($file['path']));

并且它有效 - 在我也完全删除了错误的$header

之后

:)