使用PHP Curl上传多张图片

8

我正在尝试使用PHP Curl上传多张图片。我正在使用的API给出了以下示例:

curl -v -s -u username:password \
 -H "Content-Type: multipart/form-data" \
 -H "Accept: application/vnd.com.example.api+json" \
 -F "image=@img1.jpeg;type=image/jpeg" \
 -F "image=@img2.jpeg;type=image/jpeg" \
 -XPUT 'https://example.com/api/sellers/12/ads/217221/images'

所以在我的php脚本中,我尝试了这样:

$files = array();

foreach($photos as $photo) {
    $cfile = new CURLFile('../' . $photo, 'image/jpeg', 'test_name');
    $files[] = $cfile;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://services.example.com/seller-api/sellers/' . $seller . '/ads/' . $voertuig_id . '/images');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $files);
curl_setopt($ch, CURLOPT_PROXY,'api.test.sandbox.example.com:8080');
curl_setopt($ch, CURLOPT_USERPWD, 'USER:PASS');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Host: services.example.com',
    'Content-type: multipart/form-data; boundary=vjrLefDejJaWiU0JzZfsadfasd1rMcE2HQ-n7XsSx',
    'Accept: application/vnd.com.example.api+json'
));

$output = curl_exec($ch);

curl_close($ch);

首先,我从API中获取了以下响应:

 {
   "errors":{
      "error":{
         "@key":"unsupported-form-element"
      }
   }
}

但现在完全没有响应。

我如何使用curl上传多个文件?

如果$files是一个空的JSON,例如,它根本不会给出任何错误并返回图像(当然是空的)。

这是我正在使用的API文档:https://services.mobile.de/manual/new-seller-api.html#_upload_images

编辑:我尝试构建请求主体并发送它,但它不起作用:

$requestBody = '';
$requestBody .= '--vjrLeiXjJaWiU0JzZkUPO1rMcE2HQ-n7XsSx\r\n';
$requestBody .= 'Content-Disposition: form-data; name="image"; filename="ferrari.JPG"\r\n';
$requestBody .= 'Content-Type: image/jpeg\r\n';
$requestBody .= 'Content-Transfer-Encoding: binary\r\n';

curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
1个回答

3

尝试使用关联数组,如何在文档CURLFile中使用它。

$photos = [
    'img1' => 'img1.jpg',
    'img2' => 'img2.jpg'
]

$files = [];

foreach($photos as $key => $photo) {
    $cfile = new CURLFile('../' . $photo, 'image/jpeg', $key);
    $files[$key] = $cfile;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://services.example.com/seller-api/sellers/' . $seller . '/ads/' . $voertuig_id . '/images');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $files);
curl_setopt($ch, CURLOPT_PROXY,'api.test.sandbox.example.com:8080');
curl_setopt($ch, CURLOPT_USERPWD, 'USER:PASS');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Host: services.example.com',
    'Content-type: multipart/form-data; boundary=vjrLefDejJaWiU0JzZfsadfasd1rMcE2HQ-n7XsSx',
    'Accept: application/vnd.com.example.api+json'
));

$output = curl_exec($ch);

curl_close($ch);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接