CURL:将带边界的图像发送到REST API

时间:2017-06-08 09:29:33

标签: php rest curl

我目前正在使用某种API。我编写了简单的函数,允许我添加新内容,但我坚持上传图像。

这是文档中的简单CURL命令:

curl -v -s -u username:password \
  -H "Content-Type: multipart/form-data" \
  -H "Accept: application/api+json" \
  -F "image=@img1.jpeg;type=image/jpeg" \
  -F "image=@img2.jpeg;type=image/jpeg" \
  -XPUT ''

示例请求:

PUT /images HTTP/1.1
Host: example
Content-Type: multipart/form-data; boundary=vjrLeiXjJaWiU0JzZkUPO1rMcE2HQ-n7XsSx

--vjrLeiXjJaWiU0JzZkUPO1rMcE2HQ-n7XsSx
Content-Disposition: form-data; name="image"; filename="img1.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary

现在,有我的功能:

$headers_put = array( 
   "Content-Type: multipart/form-data; boundary=vjrLeiXjJaWiU0JzZkUPO1rMcE2HQ-n7XsSx",
   "Accept: application/+json",  
); 

function putImages($ch, $headers, $ad, $images){
    $url = '/images';

    $files = [];

    foreach($images as $key => $image) {
        $number = $key +1;
        $paths = parse_url($image, PHP_URL_PATH);
        $paths = $_SERVER['DOCUMENT_ROOT'] . $paths;

        $cfile = new CURLFile(''. $paths, 'image/jpeg', 'image'.$key);
        $files[$key] = $cfile;

    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $files);

    $result = curl_exec($ch);
    var_dump($result);

    echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
    echo "\n";

}

最后,回复是:

{"errors":{"error":{"@key":"unsupported-form-element"}}}"

我做错了什么?有任何想法吗?谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

使用curl_file_create后几种方法没有让它工作。我认为mobile.de-API刚刚实施得很糟糕。

我最终为CURLOPT_POSTFIELDS实现了一个自定义例程,即手动创建完整的multipart。我从PHP手册页中借用了大部分代码作为“CURLFile类”。

  1. 创建文件名数组
  2. 创建多部分标题(请参阅下面的代码)

    function curl_custom_postfields(array $files = array())    {
    
    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"image\"",
            "Content-Type: image/jpeg",
            "",
            $data,
        ));
    }
    
    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));
    
    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });
    
    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";
    
    // set options
    return array(implode("\r\n", $body), $boundary);    
    }
    
  3. 使用该功能;)

    $postfields = $this->curl_custom_postfields($files);
    
  4. 为http标头添加边界

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; boundary=' . $postfields[1], 'Accept: application/vnd.de.mobile.api+json'));
    
  5. 添加Postfields

    curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields[0]);
    
  6. 这根本不是最干净的解决方案,所以请小心使用。但至少它有效。

答案 1 :(得分:0)

我遇到了同样的问题并找到了解决办法,但仅适用于单张图片。 诀窍是你的数组必须如下所示:

$images = array(
  'image' => 'PATH/IMG.jpg',
);

这意味着密钥必须是" image"没有别的! 我希望有所帮助;)