【问题标题】:POST binary file using curl使用 curl POST 二进制文件
【发布时间】:2011-08-06 01:20:18
【问题描述】:

我有一个基本的上传表单,我想使用 cURL 进行模拟。

<?php
$params = array(
    'api_key' => $api_key,
    'api_secret' => $api_secret,
    'urls' => null,
    'uids' => 'all',
    'detector' => 'Aggressive',
    'namespace' => 'face.auth');

$action = $url . '?' . http_build_query($params);
?>

<form enctype="multipart/form-data" method="post" action="<?php echo $action; ?>">  
    <input type="file" name="upload" id="upload">
    <input type="submit" />
</form>

我知道如何使用 cURL 发布,但我不确定如何发布图像数据(此数据作为二进制数据存储在数据库中,我们称之为 $binary)。传递$binary 如下所示作为邮递区不起作用。我看过一些示例,它们将@ 放在文件名/路径前面,并将其作为后域发送。但是,这似乎对我不起作用(因为我处理的是二进制数据,而不是文件名/路径)。

$params = array(
    'api_key' => $api_key,
    'api_secret' => $api_secret,
    'urls' => null,
    'uids' => 'all',
    'detector' => 'Aggressive',
    'namespace' => 'face.auth',
    $binary);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);      
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

var_dump($data);

?>

我也试过了:

    $params = array(
            'api_key' => $api_key,
            'api_secret' => $api_secret,
            'urls' => null,
            'uids' => 'all',
            'detector' => 'Aggressive',
            'namespace' => 'face.auth');


$action = $url . '?' . http_build_query($params);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $action);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $binary);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

任何帮助将不胜感激。

【问题讨论】:

标签: php curl http-post


【解决方案1】:

没有必要像@Piskvor 在POST a file string using cURL in PHP? 中构建的那样构建完整的数据字符串来实现这一点......我们可以通过在数组中传递二进制数据来做到这一点......

由于 curl 在内部执行相同的字符串构建“Piskvor”在上述问题中所做的...

当 curl 在 postfield 中获取数组时 curl 将该数据视为“multipart/form-data”

但要实现这一点,我们只需要在数组键中进行小修复,我们将在其中传递二进制数据...请在下面检查您是否需要传递 binaryData,如下所示...瞧,您将在 $_files 中得到它远程 url 上的数组

$params['image";filename="image'] = $binaryData

现在,它是如何实现的:

只有当远程服务器在 curl 构建的帖子字符串中获得 filename="some_name" 属性时,远程服务器才会识别您的帖子数据。 '不明白它是文件...所以我们在 post 数组而不是文件数组中获得二进制内容....

如果您的代码中的上述小改动不起作用,请告诉我......因为它对我有用......我喜欢分享这个......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2013-02-01
    • 2012-07-07
    • 1970-01-01
    相关资源
    最近更新 更多