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

使用Google Drive PHP库通过ID获取文件名时遇404错误求助

问题描述

使用Google PHP库搭配服务账号,尝试通过文档ID获取共享团队盘中的文档名称。该服务账号是共享盘的内容管理者,但执行代码时出现404错误:文件未找到。

PHP代码

$client = new \Google_Client();
$client->setApplicationName('Google API Test');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('credentials.json');

$service = new \Google_Service_Drive($client); 

$files = $service->files->get('xxxxxxxxxxxxxxxxxxxxxxxxxxx');

echo "File Name: " . $file->getName();

完整错误信息

PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 404,
    "message": "File not found: xxxxxxxxxxxxxxxxxxxxxxxxxxx.",
    "errors": [
      {
        "message": "File not found: xxxxxxxxxxxxxxxxxxxxxxxxxxx.",
        "domain": "global",
        "reason": "notFound",
        "location": "fileId",
        "locationType": "parameter"
      }
    ]
  }
}
解决办法
  • 修正变量名错误:代码中把文件对象赋值给了$files,但输出时调用的是未定义的$file,先修正这个问题:将$files = $service->files->get(...)改为$file = $service->files->get(...)。
  • 添加团队盘支持参数:访问共享团队盘中的文件必须在get方法里指定supportsAllDrives参数为true,否则API无法识别团队盘内的文件。修改后的调用代码:
$file = $service->files->get('xxxxxxxxxxxxxxxxxxxxxxxxxxx', [
    'supportsAllDrives' => true
]);
  • 核对基础信息:确认服务账号确实拥有该团队盘的内容管理者权限,同时检查文档ID是否完全正确,避免输入错误或多余字符。
  • 验证作用域:当前使用的DRIVE作用域权限足够,但如果问题仍存在,可以尝试替换为DRIVE_READONLY作用域,确保权限范围匹配操作需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:12:18