如何使用PHP共享任何人Google Drive API的文件

时间:2017-07-04 18:28:47

标签: php google-api google-drive-api google-api-php-client google-api-client

我一直在尝试,但无法达到任何结果。 代码正在生成权限ID,我不知道这意味着什么。

如果之前有人成功,请提供帮助,我只想使用google drive api v2.0公开分享文件

$fileId = '18mWN0UWX_z-4A1gag85ou0Im-wvKfMZU-tibdVd8nxY';
$userPermission = new Google_Service_Drive_Permission(array(
    'type' => 'anyone',
    'role' => 'reader',
    'emailAddress' => 'user@example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $userPermission, array('fields' => 'id'));
  $batch->add($request, 'user');
  $domainPermission = new Google_Service_Drive_Permission(array(
    'type' => 'domain',
    'role' => 'reader',
    'domain' => 'example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $domainPermission, array('fields' => 'id'));
  $batch->add($request, 'domain');
  $results = $batch->execute();

  foreach ($results as $result) {
    if ($result instanceof Google_Service_Exception) {
      // Handle error
      printf($result);
    } else {
      printf("Permission ID: %s\n", $result->id);
    }
  }
} finally {
  $service->getClient()->setUseBatch(false);
}

2 个答案:

答案 0 :(得分:1)

这是我2年前的代码片段。

$uplodedOriginalFile = new Google_Service_Drive_DriveFile();
$originallinkdata = file_get_contents($downloadlink['originallink']);
$uploadedfile = $service->files->insert($uplodedOriginalFile, array(
              'data' => $originallinkdata,
              'uploadType' => 'multipart',
            ));

$newPermission = new Google_Service_Drive_Permission();
//$newPermission->setValue($value);
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try 
{
    $service->permissions->insert($uploadedfile['id'], $newPermission);
} 
catch (Exception $e) 
{
    print "An error occurred: " . $e->getMessage();
}

$publicOriginallink = "https://googledrive.com/host/".$uploadedfile['id'];

所以你只需要插入的文件ID,并保留任何人作为读者的permssion,并在“https://googledrive.com/host/ [google drive sdk返回的新插入的文件ID]后附加插入的文件ID”

答案 1 :(得分:0)

代码段有效

struct UserId(u64);

我只是对Jai的代码(Google_Permission)进行了一些更改,以使其与我的Google API客户端库版本相匹配。