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

如何使用CodeIgniter4与cURL通过外部API上传大JSON文件

大JSON文件POST上传至外部API的解决方案(CodeIgniter4)

核心概念澄清

  • 直接本地传输:如果你的CodeIgniter4应用运行在可访问本地桌面文件的环境(比如本地开发环境、服务器挂载了桌面目录),可以直接读取本地JSON文件内容发送给外部API,无需先上传到云服务器。
  • 先传至自身服务器:如果是普通用户通过浏览器上传本地JSON文件到你的CI4应用,再由应用转发给外部API,这种场景下需要先将文件接收至服务器临时目录,再处理发送。

场景1:直接读取本地JSON文件发送到外部API

适用于CI4应用能直接访问目标JSON文件的场景,采用流式传输避免大文件占用过多内存。

CI4实现代码

<?php
namespace App\Controllers;

use CodeIgniter\Controller;

class ApiUpload extends Controller
{
    public function sendLargeJson()
    {
        // 本地JSON文件的实际路径(根据你的桌面路径修改)
        $jsonFilePath = '/Users/yourname/Desktop/large_data.json';
        
        // 校验文件可用性
        if (!file_exists($jsonFilePath) || !is_readable($jsonFilePath)) {
            die('目标文件不存在或无读取权限');
        }

        $externalApiUrl = 'https://your-external-api.com/upload-endpoint';
        
        // 初始化CURL并配置流式传输
        $ch = curl_init($externalApiUrl);
        $fileHandle = fopen($jsonFilePath, 'r');
        
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fileHandle);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . filesize($jsonFilePath)
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 设置5分钟超时,适配大文件传输
        
        // 执行请求并处理结果
        $response = curl_exec($ch);
        
        if (curl_errno($ch)) {
            $errorMsg = curl_error($ch);
            curl_close($ch);
            fclose($fileHandle);
            die('请求失败:' . $errorMsg);
        }
        
        // 释放资源
        curl_close($ch);
        fclose($fileHandle);
        
        // 打印API响应
        echo '<pre>';
        print_r(json_decode($response));
        echo '</pre>';
    }
}

场景2:用户上传JSON文件到CI4服务器后转发至外部API

适用于前端用户上传文件到你的应用,再由应用中转到外部API的场景。

CI4后端处理代码

<?php
namespace App\Controllers;

use CodeIgniter\Controller;

class UserUpload extends Controller
{
    public function uploadAndForward()
    {
        // 配置文件上传规则
        $config = [
            'upload_path'   => WRITEPATH . 'uploads/', // CI4默认临时上传目录
            'allowed_types' => 'json',
            'max_size'      => 20480, // 限制20MB,可按需调整
            'overwrite'     => true
        ];

        $this->load->library('upload', $config);
        
        // 处理用户上传
        if (!$this->upload->do_upload('json_file')) {
            echo $this->upload->display_errors();
            return;
        }
        
        // 获取上传后的文件信息
        $uploadData = $this->upload->data();
        $uploadedFilePath = $uploadData['full_path'];
        
        // 转发到外部API
        $externalApiUrl = 'https://your-external-api.com/upload-endpoint';
        $ch = curl_init($externalApiUrl);
        
        $fileHandle = fopen($uploadedFilePath, 'r');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fileHandle);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . filesize($uploadedFilePath)
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        
        $response = curl_exec($ch);
        
        // 清理服务器临时文件(可选)
        unlink($uploadedFilePath);
        
        if (curl_errno($ch)) {
            $errorMsg = curl_error($ch);
            curl_close($ch);
            fclose($fileHandle);
            die('转发失败:' . $errorMsg);
        }
        
        curl_close($ch);
        fclose($fileHandle);
        
        // 打印API响应
        echo '<pre>';
        print_r(json_decode($response));
        echo '</pre>';
    }
}

前端上传表单

<form method="post" action="/userupload/uploadandforward" enctype="multipart/form-data">
    <input type="file" name="json_file" accept=".json" required>
    <button type="submit">上传并转发</button>
</form>

关键注意事项

  • 内存优化:必须用fopen获取文件指针进行流式传输,禁止用file_get_contents一次性加载大文件到内存,避免内存溢出。
  • 超时配置:大文件传输耗时较长,需调整CURL的CURLOPT_TIMEOUT以及PHP的max_execution_time参数。
  • API兼容性:提前确认外部API支持大体积JSON POST请求,部分API可能要求用multipart/form-data格式上传,需对应调整请求头和参数。
  • 权限检查:确保CI4应用有读取本地文件、写入上传目录的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:45:32