无法将文件上传至Google Drive指定文件夹的问题求助
解决Google Drive PHP API上传文件到指定文件夹失效问题
看起来你遇到的核心问题是类名使用错误,导致Google_Service_Drive_ParentReference无法被识别,代码执行到这里直接报错中断,所以你加的die()没机会输出。
问题分析
你当前使用的是旧版的Google API PHP客户端(通过contrib/Google_DriveService.php引入),这个版本里的父文件夹引用类是Google_ParentReference,而不是Google_Service_Drive_ParentReference——后者是新版客户端(基于Google_Service_Drive)的类名,和你当前的依赖不兼容。
修正后的完整代码
require_once 'google-api-php-client/src/Google_Client.php'; require_once 'google-api-php-client/src/contrib/Google_DriveService.php'; // 开启错误提示,方便调试(生产环境建议关闭) error_reporting(E_ALL); ini_set('display_errors', 1); session_start(); // 确保session已启动,accessToken需要存在session里 $url = '你的回调URL'; // 替换成实际的回调地址 $client = new Google_Client(); $client->setClientId('xxxxxxxxxxxxxxxx'); $client->setClientSecret('xxxxxxxxxxxxxxxx'); $client->setRedirectUri($url); $client->setScopes(array('https://www.googleapis.com/auth/drive')); if (isset($_GET['code'])) { $_SESSION['accessToken'] = $client->authenticate($_GET['code']); header('location:'.$url); exit; } elseif (!isset($_SESSION['accessToken'])) { $client->authenticate(); } $files= array(); $dir = dir('files'); while ($file = $dir->read()) { if ($file != '.' && $file != '..') { $files[] = $file; } } $dir->close(); if (!empty($_POST)) { $client->setAccessToken($_SESSION['accessToken']); $service = new Google_DriveService($client); $finfo = finfo_open(FILEINFO_MIME_TYPE); $folderId="1dFcg7LbUsXsAfKn_IpntdffssMT92aQiskEr7p"; // 确认这个文件夹ID是正确的 foreach ($files as $file_name) { $file_path = 'files/'.$file_name; $mime_type = finfo_file($finfo, $file_path); $file = new Google_DriveFile(); $file->setTitle($file_name); $file->setDescription('This is a '.$mime_type.' document'); $file->setMimeType($mime_type); // 设置父文件夹 if ($folderId != null) { // 替换为正确的类名 $parent = new Google_ParentReference(); $parent->setId($folderId); $file->setParents(array($parent)); // echo "<pre>ok</pre>"; // 现在应该能输出了 } else { echo "no folder found"; } try { $createdFile = $service->files->insert( $file, array( 'data' => file_get_contents($file_path), 'mimeType' => $mime_type ) ); // 可选:打印上传后的文件ID,验证是否成功 echo '上传成功,文件ID: ' . $createdFile->getId() . '<br>'; } catch (Exception $e) { echo '上传失败,错误信息: ' . $e->getMessage() . '<br>'; } } finfo_close($finfo); // header('location:'.$url);exit; // 可以先注释掉,看调试信息 }
额外注意事项
- 确保
$folderId是正确的Google Drive文件夹ID,可以在文件夹的URL中找到(比如https://drive.google.com/drive/folders/XXX里的XXX)。 - 确认你的OAuth 2.0客户端已授权
https://www.googleapis.com/auth/drive权限,且当前的accessToken拥有该文件夹的写入权限。 - 确保
files目录存在且有可读权限,里面的文件能被file_get_contents读取。 - 建议开启错误提示(代码里已加),方便排查后续可能出现的问题。
内容的提问来源于stack exchange,提问作者Rishabh Kushwaha
相关产品推荐
相关产品推荐

