2017-02-16 173 views
0

當我嘗試通過Google API上傳文件到Google雲端硬盤時(https://github.com/google/google-api-php-client),我收到錯誤「權限不足」(讀取的文件沒有任何問題)。這裏是代碼示例:無法通過Google API將文件上傳到Google雲端硬盤

require_once 'google-api-php-client/vendor/autoload.php'; 

class GoogleConnector { 
    private $client; 
    public $report; 

    function __construct($filesToSend, $backupFolder) { 
     session_start(); 
     $this->client = new Google_Client(); 
     $this->client->setAuthConfig('client_secret.json'); 
     $this->client->addScope("https://www.googleapis.com/auth/drive"); 
     //also try different variants of this: 
     //$this->client->setScopes(implode(' ', array(Google_Service_Drive::DRIVE))); 

     if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
      $this->client->setAccessToken($_SESSION['access_token']); 
      $service = new Google_Service_Drive($this->client); 
      $folderId = "FolderIdFromGoogleDrive"; 

      $this->report = ""; 
      foreach ($filesToSend as $file) { 
       $this->report .= $this->uploadFile($file, $folderID, $service); 
      } 
     } 
     else { 
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/googleapi/oauth2callback.php'; 
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
     } 
    } 

    function uploadFile($fileName, $folderID, Google_Service_Drive $driveService) { 
     $fileMetadata = new Google_Service_Drive_DriveFile(array(
       'name' => $fileName, 
       'parents' => array($folderId) 
     )); 

     try { 
      $content = file_get_contents($fileName); 
      $file = $driveService->files->create($fileMetadata, array(
        'data' => $content, 
        'mimeType' => 'application/x-gzip', 
        'uploadType' => 'multipart', 
        'fields' => 'id')); 
      return "File '$fileName' uploaded with id '$file->id'" . PHP_EOL; 
     } 
     catch (Exception $exc) { 
      return "Error working with file '$fileName':" . $exc->getMessage(); 
     } 
    } 
} 

我該如何解決它?

+0

確保您使用驗證用戶可以訪問「FolderIdFromGoogleDrive – DaImTo

+0

我只使用一個用戶和該用戶可以創建內部文件‘通過谷歌驅動的網站FolderIdFromGoogleDrive’。 – Varro

+0

顯然,如果你得到「權限不足」,試着做一個file.list,並確保該文件夾出現給用戶,如果出現然後重新認證用戶,你必須使用差別範圍認證一次,然後 – DaImTo

回答

相關問題