我想使用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正文。
POST
请求,使用multipart/form-data
媒体类型,其中HTTP正文是一系列MIME部分,文件数据在一个部分中,通常在其他部分中用于描述文件或提供其他字段额外的输入。
要使用Indy发送multipart/form-data
编码的POST
请求,您需要使用以TIdHTTP.Post()
对象作为输入的TIdMultipartFormDataStream
方法的重载版本。然后,您可以根据需要将文件(和其他字段)添加到TIdMultipartFormDataStream
。