php - 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'),
]
解决方案
“尝试使用索引值发送”实际上您使用的是字符串,而不是数组的值。
用一个真实的数组试试:
CURLOPT_POSTFIELDS => [
'file' => [
new CURLFile('Image.png','image/png', 'Image.png'),
new CURLFile('Image2.png','image/png', 'Image2.png'),
]
];
类名CURLFile
不是CURLFILE
or CurlFile
。
构造函数签名不允许参数中的数组:
public __construct ( string $filename , string|null $mime_type = null , string|null $posted_filename = null )
您的代码应该会给您一些错误,您应该在日志中查找它们或在浏览器中启用打印它们(设置display_errors
为true
)
推荐阅读
- firebase - google firebase trigger 一次只能接收一次 google pub/sub 消息吗
- python - 非零值的 opencv meanStdDev
- maven - 和有什么区别
测试 和编译 ? - python - 如何有效地检查第一个具有python概念的列表
- analytics - 如果所有用户都已注册,如何处理 Mixpanel 的别名功能?
- javascript - 连续运行代码而不是 do-while 循环的替代方法?
- javascript - 如何在保留页面内容的同时创建上一个和下一个按钮
- excel - 多列列表框 - 添加项目:无效或不合格的参考
- mysql - 选择总和如果并且有计数
- python - 以块大小读取 39GB CSV 文件数据。我无法以一种 df 格式附加块