【问题标题】:Curl exec using Indy10使用 Indy10 进行卷曲执行
【发布时间】:2020-04-13 20:06:19
【问题描述】:

我想使用 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.';
    }

【问题讨论】:

    标签: curl delphi-2010 indy10


    【解决方案1】:

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

    • 以文件数据作为 HTTP 正文的 PUT 请求。

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

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

    【讨论】:

    • 它让我走上了正确的道路。我已经使用 TIdMultiPartFormDataStream 和 AddFile('image',) 完成了它。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2016-04-23
    • 1970-01-01
    相关资源
    最近更新 更多