Search code examples
curldelphi-2010indy10

Curl exec using Indy10


I would like to do the next curl request (php) using Delphi 2010 and Indy10 (IdHttp component), but I'm not sure if It could be done. I can do GET, PUT and POST (CRUD) with IdHttp component, but in this case I don't know how to implement it. I'm not interested in how to simulate curl commands with Delphi, but how to implement this specific POST to upload a file.

   $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.';
    }

Solution

  • There are generally two ways to upload a file with HTTP:

    • a PUT request with the file data as the HTTP body.

    • a POST request using the multipart/form-data media type, where the HTTP body is a series of MIME parts, with the file data in one part, and usually additional fields in other parts to describe the file, or provide extra input.

    To send a multipart/form-data encoded POST request with Indy, you need to use the overloaded version of the TIdHTTP.Post() method that takes a TIdMultipartFormDataStream object as input. You can then add your file(s) (and other field(s)) to the TIdMultipartFormDataStream as needed.