使用Google Drive API导出文件遇403错误求助(支持共享驱动器)
解决Google Drive API导出Google表格时的403 fileNotExportable错误
核心问题排查与修复步骤
1. 给export方法补充supportsAllDrives参数
你确实漏了在export调用中传入supportsAllDrives参数——如果目标文件存放在共享驱动器中,这个参数是必须的,否则API无法正确识别文件的位置权限,进而触发错误。
修改后的export调用代码:
$response = $service->files->export( $file->getId(), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ["supportsAllDrives" => true] // 新增此参数 );
2. 验证文件是否为原生Google表格
错误提示“Export only supports Docs Editors files”的另一个常见原因是:你操作的文件并非原生Google表格(即通过Google Drive创建的.gsheet文件),而是上传的Excel文件(MIME类型为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)。这种情况下不能用export方法,需要改用getMedia下载:
// 如果是上传的Excel文件,替换export为getMedia $response = $service->files->get( $file->getId(), ["alt" => "media", "supportsAllDrives" => true] );
你可以先通过get方法返回的$file对象确认文件类型:
echo $file->getMimeType(); // 原生Google表格应该返回:application/vnd.google-apps.spreadsheet
3. 确认服务账号的权限
确保你使用的服务账号邮箱(在GOOGLE_SA_JSON文件中可找到client_email字段)已经被授予目标文件的至少查看权限——如果文件在共享驱动器中,还需要确保服务账号被添加到该共享驱动器的成员列表中。
完整修正后的代码示例
$client = new Google_Client(); $client->setApplicationName('My API'); $client->setScopes([ Google_Service_Drive::DRIVE_METADATA_READONLY, Google_Service_Drive::DRIVE_READONLY, Google_Service_Drive::DRIVE_FILE, ]); $client->setAuthConfig(GOOGLE_SA_JSON); $service = new Google_Service_Drive($client); // 获取文件信息,确认类型 $file = $service->files->get(GOOGLE_STRAINS_DOC_ID, ["supportsAllDrives" => true]); $mimeType = $file->getMimeType(); // 根据文件类型选择导出/下载方式 if ($mimeType === 'application/vnd.google-apps.spreadsheet') { // 原生Google表格,使用export并传入supportsAllDrives $response = $service->files->export( $file->getId(), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ["supportsAllDrives" => true] ); } else { // 非原生文档,直接下载媒体文件 $response = $service->files->get( $file->getId(), ["alt" => "media", "supportsAllDrives" => true] ); } $temp_file = tempnam(sys_get_temp_dir(), 'myAPI'); file_put_contents($temp_file, $response->getBody()->getContents());
内容的提问来源于stack exchange,提问作者Luc Laverdure
相关产品推荐
相关产品推荐

