将输入文件从表单传递到cURL POST

时间:2016-02-05 21:28:20

标签: php html curl fat-free-framework

我有一个带有文件上传字段的表单,该字段POST到我的端点。从那里,我想将文件POST到我使用的API。

实现这一目标的最佳方式是什么?

我是否必须从临时存储中移动文件才能将其发布到API?或者我可能需要添加cURL选项?

HTML:

<form method="post" action="/my_endpoint">
    <div class="form-group">
        <label for="resume">Resume*</label>
        <input type="file" class="form-control" id="resume" name="resume" placeholder="Resume" required />
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

PHP:

$f3->route('POST /my_endpoint',
    function($f3) {
        $url = API_ENDPOINT;
        $post_params = $f3->get('POST');
        $files_params = $f3->get('FILES');

        $fields = array(
            'id' => $post_params['id'],
            'email' => $post_params['email'],
            'resume' => '@'.$files_params['resume']['tmp_name']
        );

        foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
        rtrim($fields_string, '&');

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
        curl_setopt($ch,CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
        $result = curl_exec($ch);
        curl_close($ch);
    }
);

1 个答案:

答案 0 :(得分:0)

我接受了@ Barmar的建议,创造了一个曲棍球。

$f3->route('POST /my_endpoint',
    function($f3) {
        $url = API_ENDPOINT;
        $post_params = $f3->get('POST');
        $files_params = $f3->get('FILES');

        $resume_file = curl_file_create(realpath($files_params['resume']['tmp_name']),$files_params['resume']['type'],$files_params['resume']['name']);

        $fields = array(
            'id' => $post_params['id'],
            'email' => $post_params['email'],
            'resume' => $resume_file
        );

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
        curl_setopt($ch,CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
        $result = curl_exec($ch);
        curl_close($ch);
    }
);

然后它奏效了。