You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何通过PHP CURL调用REST API上传文件至GCS及自有API?

我来帮你搞定这两个需求,咱们一步步拆解实现:

解决方案:文件上传至自有REST API并转传至Google Cloud Storage

一、完善自有API的文件接收逻辑

首先咱们先把接收文件的代码补全,确保能正确捕获上传的文件并做基础校验:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 检查文件是否上传成功且无错误
    if (isset($_FILES['files']) && $_FILES['files']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['files'];
        $fileName = $file['name'];
        $fileType = $file['type'];
        $fileTmpPath = $file['tmp_name'];
        $fileSize = $file['size'];

        // 这里可以添加自定义校验逻辑,比如限制文件类型/大小
        // 示例:只允许上传图片
        // $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        // if (!in_array($fileType, $allowedTypes)) {
        //     http_response_code(400);
        //     echo json_encode(['status' => 'error', 'message' => '仅支持上传图片文件']);
        //     exit;
        // }

        // 调用转传至GCS的函数
        uploadToGoogleCloudStorage($fileTmpPath, $fileName, $fileType);
    } else {
        // 处理文件上传错误
        $errorCode = $_FILES['files']['error'] ?? '未知错误';
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => '文件上传失败:错误码 ' . $errorCode]);
        exit;
    }
} else {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => '仅支持POST请求']);
    exit;
}

二、用PHP CURL实现文件转传至GCS

接下来实现核心的转传函数,注意PHP 5.5+推荐使用CURLFile处理文件上传(替代废弃的@语法),同时补全你未写完的CURL配置:

function uploadToGoogleCloudStorage($fileTmpPath, $fileName, $fileType) {
    // 替换为你的GCS上传接口地址
    $gcsUploadUrl = "http://acquired-backup-198200.appspot.com/upload?uname=arun&Description=description&players=arun,sai&community=true&Location=US&skills=batting";
    
    $curl = curl_init();

    // 构造POST数据:包含文件和其他参数
    $postFields = [
        'file' => new CURLFile($fileTmpPath, $fileType, $fileName),
        // 如需额外传递参数,直接在这里添加即可
        // 'extra_param' => 'custom_value'
    ];

    curl_setopt_array($curl, [
        CURLOPT_URL => $gcsUploadUrl,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postFields,
        CURLOPT_RETURNTRANSFER => true, // 捕获返回结果而非直接输出
        CURLOPT_SSL_VERIFYPEER => true, // 生产环境建议开启,保障SSL安全
        CURLOPT_TIMEOUT => 30, // 设置超时时间,避免请求挂起
        CURLOPT_FOLLOWLOCATION => true // 允许跟随重定向(如果GCS接口有跳转)
    ]);

    // 执行请求并处理响应
    $response = curl_exec($curl);
    $httpStatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $curlError = curl_error($curl);

    curl_close($curl);

    if ($curlError) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => '转传至GCS失败:' . $curlError]);
    } else {
        if ($httpStatusCode >= 200 && $httpStatusCode < 300) {
            echo json_encode(['status' => 'success', 'message' => '文件上传并转传成功', 'gcs_response' => $response]);
        } else {
            http_response_code($httpStatusCode);
            echo json_encode(['status' => 'error', 'message' => 'GCS返回错误响应', 'http_code' => $httpStatusCode, 'gcs_response' => $response]);
        }
    }
}

几个关键注意点

  • 权限验证:如果你的GCS存储桶需要身份验证,记得在CURL请求头中添加授权令牌,比如:
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer YOUR_GCS_ACCESS_TOKEN'
    ]);
    
  • 文件安全:务必在接收文件时添加类型、大小校验,避免恶意文件上传到你的服务器和GCS。
  • 兼容性CURLFile是PHP 5.5+的特性,如果你用更低版本(不推荐),可以改用@$fileTmpPath,但该写法已被废弃。

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

火山引擎 最新活动