簡體   English   中英

Google Drive PHP API不返回Google Drive文件夾

[英]Google drive php api not returning google drive folders

我正在嘗試獲取我可以在Google驅動器中看到的所有文件夾的列表。 所以我可以檢查一個文件夾,是否已經存在。 如果沒有,那么我可以創建一個。 但是谷歌驅動器PHP API返回空的文件夾列表,雖然我可以看到谷歌驅動器中的許多文件夾(通過瀏覽器)。

這是我正在使用的課程:-

<?php

class gdrive{

    //credentials (get those from google developer console https://console.developers.google.com/)

var $clientId = "1047996724365-MyID.apps.googleusercontent.com";

var $clientSecret = "MySecret";
var $redirectUri = 'http://localhost/google_drive2/gdrive_upload.php';  

    //variables
    var $fileRequest;
    var $mimeType;
    var $filename;
    var $path;
    var $client;


    function __construct(){
        require_once 'src/Google/autoload.php'; // get from here https://github.com/google/google-api-php-client.git 
        require_once 'src/Google/Client.php'; // get from here https://github.com/google/google-api-php-client.git 
        //require_once 'src/Google/Drive.php'; // get from here https://github.com/google/google-api-php-client.git 

        $this->client = new Google_Client();
    }


    function initialize(){
        //echo "<br/>initializing class\n";
        $client = $this->client;

        $client->setClientId($this->clientId);
        $client->setClientSecret($this->clientSecret);
        $client->setRedirectUri($this->redirectUri);
        $client->addScope(
    "https://www.googleapis.com/auth/drive", 
    "https://www.googleapis.com/auth/drive.appfolder");


        $refreshToken = file_get_contents(__DIR__ . "/token.txt"); 

        $client->refreshToken($refreshToken);
        $tokens = $client->getAccessToken();

        $client->setAccessToken($tokens);
        //$client->setDefer(true);
        $this->processFile();

    }

    function processFile(){

        $fileRequest = $this->fileRequest;
        //echo "Process File $fileRequest\n";
        $path_parts = pathinfo($fileRequest);
        $this->path = $path_parts['dirname'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $this->mimeType = finfo_file($finfo, $fileRequest);
        finfo_close($finfo);

        //echo "Mime type is " . $this->mimeType . "\n";

        $this->upload();

    }


/**
* Get the folder ID if it exists, if it doesnt exist, create it and return the ID
*
* @param Google_DriveService $service Drive API service instance.
* @param String $folderName Name of the folder you want to search or create
* @param String $folderDesc Description metadata for Drive about the folder (optional)
* @return Google_Drivefile that was created or got. Returns NULL if an API error occured
*/
function getFolderExistsCreate($service, $folderName, $folderDesc) {
error_reporting(E_ALL); ini_set('display_errors', 1);
    $parameters['q'] = "mimeType='application/vnd.google-apps.folder' and trashed=false";
    $files = $service->files->listFiles($parameters);
    $found = false;
    // Go through each one to see if there is already a folder with the specified name

print_r($files);exit; /****************RESPONSE ON THIS LINE *********/


    foreach ($files['items'] as $item) {
        if ($item['title'] == $folderName) {
            $found = true;
            return $item['id'];
            break;
        }
    }
    // If not, create one
    if ($found == false) {
        $folder = new Google_Service_Drive_DriveFile();
        //Setup the folder to create
        $folder->setTitle($folderName);
        if(!empty($folderDesc))
            $folder->setDescription($folderDesc);
        $folder->setMimeType('application/vnd.google-apps.folder');
        //Create the Folder
        try {
            $createdFile = $service->files->insert($folder, array(
                'mimeType' => 'application/vnd.google-apps.folder',
                ));
            // Return the created folder's id
            echo  $createdFile->id;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }





exit;

/*
        $client = new Google_Client();
        $client->setClientId($this->clientId);
        $client->setClientSecret($this->clientSecret);
        $client->setRedirectUri($this->redirectUri);

        $refreshToken = file_get_contents(__DIR__ . "/token.txt"); 

        $client->refreshToken($refreshToken);
        $tokens = $client->getAccessToken();
        $client->setAccessToken($tokens);
        $client->setDefer(true);

        $service = new Google_Service_Drive($client);
    // List all user files (and folders) at Drive root
    $parameters['q'] = "mimeType='application/vnd.google-apps.folder' and trashed=false";
    $files = $service->files->listFiles($parameters);
    print_r($files);exit;
*/
    $found = false;
    // Go through each one to see if there is already a folder with the specified name
    foreach ($files['items'] as $item) {
        if ($item['title'] == $folderName) {
            $found = true;
            return $item['id'];
            break;
        }
    }
    // If not, create one
    if ($found == false) {
        $folder = new Google_Service_Drive_DriveFile();
        //Setup the folder to create
        $folder->setTitle($folderName);
        if(!empty($folderDesc))
            $folder->setDescription($folderDesc);
        $folder->setMimeType('application/vnd.google-apps.folder');
        //Create the Folder
        try {
            $createdFile = $service->files->insert($folder, array(
                'mimeType' => 'application/vnd.google-apps.folder',
                ));
            // Return the created folder's id
            return $createdFile->id;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
}

    function upload(){
        $client = $this->client;
        $service = new Google_Service_Drive($client);

    $folderName='aaaaaaa';
     $folderDesc='Folder Desc';

// Setup the folder you want the file in, if it is wanted in a folder
    if(isset($folderName)) {
        if(!empty($folderName)) {
            //$parent = new Google_Service_Drive_ParentReference();
            //$parent->setId(getFolderExistsCreate($service, $folderName, $folderDesc));
            $parent=$this->getFolderExistsCreate($service, $folderName, $folderDesc);
            print_r($parent);exit;
            $file->setParents(array($parent));
        }
    }




        $file = new Google_Service_Drive_DriveFile(array(
  'name' => $this->filename));
        $file->title = "a.txt";
        $chunkSizeBytes = 1 * 1024 * 1024;

        $fileRequest = $this->fileRequest;
        $mimeType = $this->mimeType;

        //$request = $service->files->create($file);

        // Create a media file upload to represent our upload process.
        $media = new Google_Http_MediaFileUpload(
          $client,
          $request,
          $mimeType,
          null,
          true,
          $chunkSizeBytes
        );
        $media->setFileSize(filesize($fileRequest));

        // Upload the various chunks. $status will be false until the process is
        // complete.
        $status = false;
        $handle = fopen($fileRequest, "rb");

        // start uploading      
        //echo "Uploading: " . $this->filename . "\n";  

        $filesize = filesize($fileRequest);

        // while not reached the end of file marker keep looping and uploading chunks
        while (!$status && !feof($handle)) {
            $chunk = fread($handle, $chunkSizeBytes);
            $status = $media->nextChunk($chunk);  
        }

        // The final value of $status will be the data from the API for the object
        // that has been uploaded.
        $result = false;
        if($status != false) {
          $result = $status;
        }

        fclose($handle);
        // Reset to the client to execute requests immediately in the future.
        $client->setDefer(false);   
        ?>https://drive.google.com/open?id=<?= $result->id ?><?php
    }

}

?>

但是它返回了這個響應:

  Google_Service_Drive_FileList Object ( [collection_key:protected] => files [filesType:protected] => Google_Service_Drive_DriveFile [filesDataType:protected] => array [kind] => drive#fileList [nextPageToken] => [internal_gapi_mappings:protected] => Array ( ) [modelData:protected] => Array ( [incompleteSearch] => [files] => Array ( ) ) [processed:protected] => Array ( ) )

請告訴我我哪里錯了?

您可能需要先檢查此相關的SO帖子,其中提到出於安全原因,沒有方法可以列出用戶Drive帳戶中的所有文件。

此外,雲端硬盤API僅授予對兩類文件的訪問權限:

  • 用戶使用給定的雲端硬盤應用創建的文件
  • 用戶使用給定的雲端硬盤應用打開的文件

閱讀建議的鏈接,您可能需要管理 Google雲端硬盤中文件和文件夾的共享 而且,除了使用Permissions集合通過API管理權限外,應用程序還可以顯示標准的Google Drive共享對話框,以允許用戶共享文件。

有了權限,您可以繼續使用Files.list並在查詢參數中指定:

('root' in parents and mimeType = 'application/vnd.google-apps.folder')

那應該返回根目錄中的文件夾。 使用Try-it進行測試。

您可能需要檢查以下鏈接以獲取更多信息:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM