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

使用PHP客户端调用Google Drive API上传文件始终为0字节求助

问题解决:服务账号上传Google Drive文件显示0字节

核心错误定位

你的代码中最关键的问题是调用files->create时,第二个参数多嵌套了一层数组:

// 错误写法:多了一层[]
$file = $driveService->files->create($fileMetadata, array([
    'data' => $content,
    'mimeType' => 'text/plain',
    'uploadType' => 'multipart',
    'fields' => 'id'
]));

这种写法会把选项包裹在一个额外的数组里,导致Google API无法正确识别data参数,最终只创建了元数据,没有上传文件内容。

修正后的代码

把第二层数组的括号去掉,同时优化环境变量的写法(避免空格导致的解析问题):

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $home_path . '../google-oauth-credentials.json');

try {
    $gclient = new Google\Client();
    $gclient->useApplicationDefaultCredentials();
    $gclient->addScope('https://www.googleapis.com/auth/drive');
    $driveService = new Google\Service\Drive($gclient);

    $content = file_get_contents('testfile.txt');

    $fileMetadata = new Google\Service\Drive\DriveFile(array(
        'name' => 'test.txt',
        'parents' => array('{PARENT_ID}'),
        'description' => 'Test Description'
    ));

    // 修正:去掉多余的[],直接传递关联数组
    $file = $driveService->files->create($fileMetadata, array(
        'data' => $content,
        'mimeType' => 'text/plain',
        'uploadType' => 'multipart',
        'fields' => 'id'
    ));

    printf("File ID: %s<br>", $file->id);
    echo '<pre>' . print_r($file,1) . '</pre>';
    echo '<h1>Content:</h1>';
    echo $content;

} catch(Exception $e) {
    echo "Error Message: ".$e;
};

额外注意事项

  1. uploadType选择:
    • 仅上传文件内容(无需元数据)用media;
    • 同时上传元数据和文件内容用multipart(你的场景适合这个);
  2. fields参数:这个参数用来指定API返回的字段,比如id表示只返回文件ID,属于响应字段过滤,不影响上传结果,只是控制返回的数据量;
  3. MIME类型:文本文件用text/plain、PDF用application/pdf即可,无需用application/octet-stream(除非无法确定文件类型);
  4. 权限验证:确保目标文件夹已共享给服务账号邮箱,否则服务账号无法写入内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:50:56