如何使用PHP作为只读文件在gdrive中设置创建google doc

时间:2015-07-14 01:23:09

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

我正在使用google drive sdk在google驱动器中创建一个txt/html文件作为文档。代码成功创建文档。 我的问题是,它可以将文件权限设置为read-only文件吗?

这是我创建文档的代码,

$mkFile = $this->_service->files->insert($file, array('data' => $subcontent, 'mimeType' => 'text/html', 'convert' => true));

2 个答案:

答案 0 :(得分:1)

您可以创建仅限任何人阅读的权限。

基于文档 Google Drive API V3 的代码: https://developers.google.com/drive/api/v3/reference/permissions/create

public function permissionAnyone($fileId) {

  $permissions = new Google_Service_Drive_Permission(array(
     'role' => 'reader',
     'type' => 'anyone',
  ));

  try {
     $result = $this->service_drive->permissions->create($fileId, $permissions);
  } catch (Exception $e) {
     $result = $e->getMessage();
  }

  return $result;
}

答案 1 :(得分:0)

您可以使用permissions.patch在插入文件后更新文件的权限。目前,API中存在一个错误,您无法在插入文件时设置权限。在将文件放入驱动器后,您必须对它们进行修补。

从上面的文档链接中删除了代码。

/**
 * Patch a permission's role.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param String $fileId ID of the file to update permission for.
 * @param String $permissionId ID of the permission to patch.
 * @param String $newRole The value "owner", "writer" or "reader".
 * @return Google_Servie_Drive_Permission The patched permission. NULL is
 *     returned if an API error occurred.
 */
function patchPermission($service, $fileId, $permissionId, $newRole) {
  $patchedPermission = new Google_Service_Drive_Permission();
  $patchedPermission->setRole($newRole);
  try {
    return $service->permissions->patch($fileId, $permissionId, $patchedPermission);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}