You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP cURL调用Eden AI目标检测API传图报错:提交数据非文件

解决Eden AI目标检测API文件上传错误的方案

你遇到的错误是因为请求格式不对:当前用JSON传递文件路径,但Eden AI的API要求通过multipart/form-data格式上传实际文件,不是字符串路径。按以下方式修改代码即可解决:

关键修正点

  • 用CURLFile包装文件路径,让cURL识别这是要上传的文件
  • 移除json_encode和Content-Type: application/json头,cURL会自动处理多部分表单的请求头
  • 确保$imagePath是服务器能访问到的正确绝对路径

修正后的完整代码

public function index() {
    $ch = curl_init();

    $url = "https://api.edenai.run/v2/image/object_detection";
    $apiKey = "my_api_key";
    $imagePath = "/ise/myimage.jpg";
    
    // 用CURLFile包装文件,确保cURL正确处理文件上传
    $data = array(
        'providers' => 'api4ai, clarifai, amazon, google, microsoft, sentisight',
        'file' => new CURLFile($imagePath)
    );
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    // 直接传递数组,cURL会自动转为multipart/form-data格式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $apiKey
        // 不再设置Content-Type,cURL会自动处理
    ));
    
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    
    curl_close($ch);
    
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput($response);
}

额外注意事项

  • 如果$imagePath是相对路径,要确保脚本执行时能正确找到文件,比如可以用realpath($imagePath)获取绝对路径,避免因工作目录问题找不到文件:
    $imagePath = realpath('./myimage.jpg'); // 替换为你的相对路径
    
  • 确认服务器有该文件的读取权限,避免因权限问题导致上传失败。

内容的提问来源于stack exchange,提问作者Mohammad Massri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 06:31:13