curl发送请求上传文件(multipart file upload)

版权声明:原创文章,转载声明出处 https://blog.csdn.net/weixin_43183475/article/details/82631263

折腾一下午的问题

第三方接口需要我们传multipart 上传文件
curl一直各种试不成功,用Restlet Client工具总是能成功!
对比发送的头,发现工具在Content-Type: multipart/form-data;后面多了个这个boundary
然后去查了下,果真问题在这,哎,下面代码给自己做个笔记

$file = [
    'http://imgcdn.taobao.com/test/_2a501d5fd1bc84fa6b29d648fb3f37ea.jpeg',
    'http://imgcdn.taobao.com/test/_e0274d5ba694062e8b2ba4619c5002a8.jpeg',
];
curl_put($file);
function read_file($file)
{
    $fh = fopen($file, 'r') or die($file.'打开失败');
    $con = stream_get_contents($fh);
    fclose($fh);
    return $con;
}
function curl_put($data)
{
    $token = 'yaiWD9f30UxsRJphtqTw3Nom5360R8u3slYN';
    $header = [
        "X-Channel-Authorization:".$token,
    ];

    $ch = curl_init(); //初始化CURL句柄
    curl_setopt($ch, CURLOPT_URL, 'https://api-demo.xxxx.com/?docType=IDENTITY_CARD&appId=55568547'); //设置请求的URL
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
    curl_custom_postfields($ch , $data , $header);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);//设置超时时间
    $result = curl_exec($ch);
    var_dump($result);
    echo $http_status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
function curl_custom_postfields($ch, array $files = array() , array $header = array() ) {


    foreach ($files as $k => $v) {
        $data = read_file($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"docFiles\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $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 @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array_merge($header , array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        )),
    ));
}

猜你喜欢

转载自blog.csdn.net/weixin_43183475/article/details/82631263