我从谷歌驱动器文档中得到了我的问题的答案......可以将从服务帐户上传的文件共享到任何谷歌驱动器帐户。只是我们必须为我们必须查看该文件的驱动器帐户提供该特定文件的权限......我的代码如下:
<?php
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/contrib/Google_Oauth2Service.php";
session_start();
function buildService() {
$DRIVE_SCOPE = array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://gdata.youtube.com/action/GetUploadToken', 'https://gdata.youtube.com');
$SERVICE_ACCOUNT_EMAIL = 'SOMETHING@developer.gserviceaccount.com';
if($_SERVER['HTTP_HOST'] == 'localhost')
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'YOUR_CERTIFICATE-privatekey.p12';
else
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = $_SERVER['DOCUMENT_ROOT'].'YOUR_CERTIFICATE-privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
$DRIVE_SCOPE,
$key);
$client = new Google_Client();
$client->setApplicationName("You Tube API");
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
$client::$auth->refreshTokenWithAssertion();
$json = $client->getAccessToken();
$accessToken = json_decode($json)->access_token;
return new Google_DriveService($client);
}
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
//print 'File ID: %s'.$createdFile->getId();
//print 'Parent ID<pre>'.print_r($createdFile->getParents())."</pre>";
$fileId = $createdFile->getId();
$file = $service->files->get($fileId);
$newPermission = new Google_Permission();
$newPermission->setValue('DRIVE_ACCOUNT_TO_SHARE@gmail.com');
$newPermission->setType('user');
$newPermission->setRole('reader');
try {
return $service->permissions->insert($createdFile->getId(), $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$service = buildService();
$createdFile=insertFile($service, 'Testing', 'Testing for file upload', 'Parent_Id_', 'application/pdf', 'test.pdf');
echo "<pre>".print_r($createdFile)."</pre>";
?>