PHP使用cURL向FastAPI上传多张同key图片失败如何解决
多文件上传至FastAPI接口的PHP cURL适配方案
核心原理
FastAPI接收多文件上传时,要求表单提交同名字段files的多组值,PHP中无需使用带索引的files[0]/files[1]格式,只需将键名设置为files[]即可匹配FastAPI的字段解析规则。
推荐实现方案(PHP >= 7.2)
PHP 7.2及以上版本支持CURLOPT_MIMEPOST参数,可更稳定地构建multipart表单:
<?php // 替换为实际FastAPI接口地址 $apiUrl = 'http://你的服务地址/predict/skin/oil'; // 待上传的图片路径列表 $imagePaths = [ '/data/images/1.jpg', '/data/images/2.jpg', '/data/images/3.jpg' ]; $postFields = []; foreach ($imagePaths as $filePath) { if (!file_exists($filePath)) continue; // 构造CURLFile对象 $curlFile = curl_file_create( realpath($filePath), mime_content_type($filePath), basename($filePath) ); // 键名固定为files[],无需加索引 $postFields[] = [ 'name' => 'files[]', 'contents' => $curlFile ]; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_MIMEPOST, $postFields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if (curl_errno($ch)) { $errorMsg = curl_error($ch); // 按需添加错误处理逻辑 } curl_close($ch); // 处理接口返回结果 var_dump($response); ?>
低版本PHP兼容方案(PHP < 7.2)
如果PHP版本不支持CURLOPT_MIMEPOST,可使用以下写法:
<?php $apiUrl = 'http://你的服务地址/predict/skin/oil'; $imagePaths = [ '/data/images/1.jpg', '/data/images/2.jpg' ]; $postData = []; foreach ($imagePaths as $idx => $path) { $postData["files[$idx]"] = curl_file_create( realpath($path), mime_content_type($path), basename($path) ); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_POST, true); // 直接传数组,不要用http_build_query处理 curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 仅声明Content-Type,不要手动设置boundary,让cURL自动生成 curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: multipart/form-data' ]); $response = curl_exec($ch); curl_close($ch); var_dump($response); ?>
注意事项
- 禁止使用
http_build_query处理POST参数,会将文件对象转为字符串导致上传失败 - 确保上传的文件路径可读、权限正常
- 字段名必须和FastAPI接口定义的
files完全匹配,带[]后缀 - 不要手动设置multipart表单的boundary值,cURL会自动生成符合规范的分隔符
内容的提问来源于stack exchange,提问作者dinner formal
相关产品推荐
相关产品推荐

