首页 > 解决方案 > PHP CURL 使用相同的密钥上传多个文件

问题描述

我有一个rest API,它接受同一个密钥中的多个文件(用其他语言编写[肯定不是PHP])。

图片来自邮递员

通过邮递员使用了 API,我可以看到两个文件都正确上传

从邮递员生成的代码并尝试发送多个文件。

// PHP Version 7.3 +
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array(
  'file'=> new CurlFile('C:/Users/Username/Pictures/Image.png','image/png','Image.png'),
  'file'=> new CurlFile('C:/Users/Username/Pictures/Image2.png','image/png','Image2.png'),
  )
));

echo $response = curl_exec($curl);

我无法看到成功上传的两个文件。

我知道 PHP 不支持数组中的重复键。它将作为一个单独的密钥发送,即file.

但我无法控制其余的 API。它在 Postman 中运行良好。但是,PHP 没有。

有没有办法解决这个问题?

如下所示,

CURLOPT_POSTFIELDS => array(
   'file'=> new CurlFile(['Image.png','Image2.png'],'image/png', ['Image.png','Image2.png'])
);

尝试使用索引值发送,但仅适用于 PHP 到 PHP 通信(不适用于其他语言)

CURLOPT_POSTFIELDS => array(
   'file[0]'=> new CurlFile(['Image.png','Image2.png'],'image/png', ['Image.png','Image2.png']),
   'file[1]'=> new CurlFile(['Image.png','Image2.png'],'image/png', ['Image.png','Image2.png'])
);

试过索引数组,没用。

[
    new \CurlFile('image_full_path1.png', 'image/png', 'file1.png'),
    new \CurlFile('image_full_path2.png', 'image/png', 'file2.png'),
]

标签: phpcurl

解决方案


“尝试使用索引值发送”实际上您使用的是字符串,而不是数组的值。

用一个真实的数组试试:

CURLOPT_POSTFIELDS => [
    'file' => [
        new CURLFile('Image.png','image/png', 'Image.png'),
        new CURLFile('Image2.png','image/png', 'Image2.png'),
    ]
];

类名CURLFile不是CURLFILEor CurlFile

构造函数签名不允许参数中的数组:

public __construct ( string $filename , string|null $mime_type = null , string|null $posted_filename = null )

https://www.php.net/curlfile

您的代码应该会给您一些错误,您应该在日志中查找它们或在浏览器中启用打印它们(设置display_errorstrue


推荐阅读