使用 Indy10 执行卷曲

Curl exec using Indy10

我想使用 Delphi 2010 和 Indy10(IdHttp 组件)执行下一个 curl 请求 (php),但我不确定是否可以完成。我可以使用 IdHttp 组件执行 GET、PUT 和 POST (CRUD),但在这种情况下我不知道如何实现它。我对如何使用 Delphi 模拟 curl 命令不感兴趣,但对如何实现这个特定的 POST 来上传文件不感兴趣。

   $url = 'http://example.com';
    $key  = 'YOUR_GENERATED_API_ACCESS_KEY';

    $psProductId = 19;
    $urlImage = $url.'/api/images/products/'.$psProductId.'/';

    //Here you set the path to the image you need to upload
    $image_path = '/path/to/the/image.jpg';
    $image_mime = 'image/jpg';

    $args['image'] = new CurlFile($image_path, $image_mime);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
    curl_setopt($ch, CURLOPT_URL, $urlImage);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $key.':');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if (200 == $httpCode) {
        echo 'Product image was successfully created.';
    }

HTTP上传文件一般有两种方式:

  • 一个PUT以文件数据作为HTTP主体的请求。

  • a POST 使用 multipart/form-data 媒体类型的请求,其中 HTTP 正文是一系列 MIME 部分,文件数据在一个部分,通常还有附加字段在其他部分描述文件,或提供额外的输入。

要使用 Indy 发送 multipart/form-data 编码的 POST 请求,您需要使用 TIdHTTP.Post() 方法的重载版本,该方法将 TIdMultipartFormDataStream 对象作为输入。然后,您可以根据需要将文件(和其他字段)添加到 TIdMultipartFormDataStream