首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有json字符串和文件上载的cUrl

带有json字符串和文件上载的cUrl
EN

Stack Overflow用户
提问于 2017-10-26 19:11:32
回答 1查看 1.3K关注 0票数 0

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

代码语言:javascript
复制
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'"

我好像做错了什么,我找不出问题所在:

代码语言:javascript
复制
$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;
}

我尝试了几个变体,沃森视觉识别API错误现在是:

{ "custom_classes":0,“图像”:{“错误”:{“描述”:“无效图像数据。受支持的格式是JPG和PNG。”、"error_id":"input_error“}}、"images_processed":1}

在此之前:

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

谢谢你的帮助!

EN

回答 1

Stack Overflow用户

发布于 2017-10-27 11:16:30

我的问题是:

代码语言:javascript
复制
$postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);

最后一个参数是$postname。因此,为了解决这个问题,我不得不将这一行更改为:

代码语言:javascript
复制
$postData[$file['name']] = new \CURLFile($file['path'], mime_content_type($file['path']), basename($file['path']));

在我完全移除错误的$header之后,它起了作用。

:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46962077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档