【问题标题】:PHP - cURL file uploadPHP - cURL 文件上传
【发布时间】:2026-02-05 04:20:11
【问题描述】:

我正在编写一个脚本来将图像上传到特定的 api。上传一张图片不是问题,但不止一张。 API 文档说明如下:

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

我的脚本:

$ch = curl_init();

$images = array(
    'image' => new CURLFile('PATH\1.jpg', 'image/jpeg', 'image')
);

curl_setopt($ch, CURLOPT_URL, 'https://services.xxx.de/seller-api/sellers/123/ads/123/images');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $images);
curl_setopt($ch, CURLOPT_USERPWD, 'USERNAME:PASSWORD');
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.xxx.de',
    'Content-Type: multipart/form-data',
    'Accept: application/vnd.de.xxx.api+json'
));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

问题是,如果我要上传新图像,api 会删除其他图像。但是我不能像这样编写一个具有多个相同键的数组:

$images = array(
    'image' => new CURLFile('PATH\1.jpg', 'image/jpeg', 'image'),
    'image' => new CURLFile('PATH\2.jpg', 'image/jpeg', 'image')
);

所以问题是如何设置多个具有相同索引的 CURLFiles,如文档中的 curl 命令?

【问题讨论】:

  • 看这个帖子*.com/questions/44474192/…,希望对你有帮助。
  • 不,不幸的是不是因为 api 响应: {"errors":[{"key":"unsupported-form-element"}]} 这意味着 cURL-File 的键必须是“图像”,仅此而已……但非常感谢!
  • 然后在循环中尝试你的 Curl 调用。
  • 我们在谈论services.mobile.de/docs/seller-api.html 吗?他们的文档确实有多个“图像”,命名为多部分表单数据,文件名不同......多么奇怪
  • 不,我不能,因为 api 说:{"errors":[{"key":"unsupported-form-element"}]} 它必须是一个以 "image" 作为键的数组。 .

标签: php api curl


【解决方案1】:

在移动卖家 api 工作 ;-) 这是解决方案: 1. 创建一个像这样的图像文件数组:

$count=0;
$files['image'.$count] = curl_file_create(#a#, 'image/jpeg', #b#)
$count++;

-> #a# 服务器上文件的完整路径 -> #b# 可选的图像名称,格式为 'image'.$count

重要提示:数组键必须以这种方式准确命名,而您可以根据需要命名数组;-)

  1. curl 选项: - 从 HTTP_HEADER 中删除“主机” 并添加以秒为单位的 CURLOPT_CONNECTTIMEOUT 值;-)

顺便说一句,在所有实际的 php 版本中,我们使用 TRUE 和 FALSE 而不是 0 和 1 作为 curl-options 的值。

它对我有用......

【讨论】:

    【解决方案2】:

    我经过数小时的搜索后的经验: 使用官方的curl功能,不能多次上传图片。

    您只能使用 shell 命令上传多个图像。 解决方案:扩展shell脚本以包含所有要上传的图片,然后是“shell_exec($str)”或exec($str)。对我来说这是可行的。

    【讨论】: