PHP实现Google Drive上传系统文件统一存储到本人云端硬盘的方案
解决方案
你现有代码采用的是普通OAuth2授权逻辑,会引导访问站点的用户授权自己的Google Drive权限,所以文件自然会上传到发起授权的用户存储空间。要实现所有文件统一上传到你指定的个人Drive,改用服务账号(Service Account) 授权模式即可,操作步骤如下:
前置配置
- 打开Google Cloud控制台,进入你当前使用的API项目,创建服务账号,生成JSON格式的密钥文件,将密钥文件上传到你的PHP项目可读取的目录中,注意不要放在公网可访问的路径下避免泄漏
- 进入你自己的Google Drive,找到代码中指定的上传目标文件夹(ID为
1NyNNtNHKRqZJiwT7eTskvLzG7O9xR9oy),将该文件夹的「编辑权限」共享给刚才创建的服务账号的邮箱地址(服务账号信息页可查看该邮箱)
代码调整
删掉原有引导用户授权的全部逻辑,改用服务账号初始化客户端,修改后代码如下:
session_start(); if(!empty($_FILES['fileToUpload'])) { require_once 'google-api-php-client/src/Google_Client.php'; require_once 'google-api-php-client/src/contrib/Google_DriveService.php'; require_once 'google-api-php-client/src/auth/Google_AssertionCredentials.php'; // 替换为你自己的服务账号密钥文件的实际存储路径 $service_account_key = '/path/to/your/service-account-key.json'; $key_data = json_decode(file_get_contents($service_account_key), true); $client = new Google_Client(); $client->setApplicationName('Drive File Upload'); $client->setScopes(array('https://www.googleapis.com/auth/drive')); // 初始化服务账号凭证 $cred = new Google_AssertionCredentials( $key_data['client_email'], array('https://www.googleapis.com/auth/drive'), $key_data['private_key'] ); $client->setAssertionCredentials($cred); // 直接初始化Drive服务,无需用户授权逻辑 $service = new Google_DriveService($client); $finfo = finfo_open(FILEINFO_MIME_TYPE); $a = array(); $k = '-1'; foreach ($_FILES['fileToUpload']['name'] as $file_name) { $k++; $file = new Google_DriveFile(); $mime_type = finfo_file($finfo, $_FILES['fileToUpload']['tmp_name'][$k]); $file->setTitle($file_name); $file->setDescription('This is a '.$mime_type.' document'); $file->setMimeType($mime_type); $parent = new Google_ParentReference(); // 该ID为你个人Drive下的目标文件夹ID,请确认已给服务账号开启编辑权限 $parent->setId('1NyNNtNHKRqZJiwT7eTskvLzG7O9xR9oy'); $file->setParents(array($parent)); $a[] = $service->files->insert( $file, array( 'data' => file_get_contents($_FILES['fileToUpload']['tmp_name'][$k]), 'mimeType' => $mime_type, ) ); } }
注意事项
- 如果你后续升级为较新版本的Google PHP API客户端,类名和自动加载逻辑会有调整,对应调整引入路径和初始化方式即可
- 必须确认目标文件夹的共享权限配置正确,否则上传的文件会存储在服务账号独立的Drive空间中,你无法在个人Drive内看到
内容的提问来源于stack exchange,提问作者Metin Saraç
相关产品推荐
相关产品推荐

