如何使用google drive api v3在根目录中列出文件/目录?

时间:2016-04-21 08:28:38

标签: php google-drive-api

我正在开发一个网站项目。我在Google Developers Console上创建了一个应用程序,并在我的服务器上安装了Google SDK。完成授权,完成离线访问,列出所有文件/目录,创建完成的文件。

现在我想列出位于根目录中的文件/目录。我的意思是只有那些并非所有子目录。

这是代码示例:

    // $client is a Google_Client object
    $service = new Google_Service_Drive($client);
    // Print the names and IDs for up to 10 files.
    $optParams = array(
        'pageSize' => 10,
        'fields' => "nextPageToken, files(contentHints/thumbnail,fileExtension,iconLink,id,name,size,thumbnailLink,webContentLink,webViewLink,mimeType,parents)",
        'q' => "trashed=false"
    );
    $results = $service->files->listFiles($optParams);

    if (count($results->getFiles()) == 0) {
        print "No files found.\n";
    } else {

        print "Files:\n";
        foreach ($results->getFiles() as $file) {
            echo "Dosya Adı: ".$file->getName()."<br>";
            echo "Dosya Id: ".$file->getId()."<br>";
            echo "Tip: ".$file->getMimeType()."<br>";
            echo "Dosya Link: ".$file->getWebContentLink()."<br>";
            echo "Dosya Link: ".$file->getWebViewLink()."<br>";
        }
    }

此代码列出了所有文件/目录(不在垃圾箱中)。我在父母身上添加了“'root'”,但它没有给我什么。没有在文档中找到任何有用的东西。

这是输出:

Files:
Dosya Adı: 1.jpg
Dosya Id: **some-id**
Tip: image/jpeg
Dosya Link: https://docs.google.com/uc?id=**some-id**&export=download
Dosya Link: https://drive.google.com/file/d/**some-id**/view?usp=drivesdk


Dosya Adı: images2
Dosya Id: **some-id**
Tip: application/vnd.google-apps.folder
Dosya Link: 
Dosya Link: https://docs.google.com/folderview?id=**some-id**&usp=drivesdk


Dosya Adı: images
Dosya Id: **some-id**
Tip: application/vnd.google-apps.folder
Dosya Link: 
Dosya Link: https://docs.google.com/folderview?id=**some-id**&usp=drivesdk


Dosya Adı: sample_01.jpg
Dosya Id: **some-id**
Tip: image/jpeg
Dosya Link: https://docs.google.com/uc?id=**some-id**&export=download
Dosya Link: https://drive.google.com/file/d/**some-id**/view?usp=drivesdk


Dosya Adı: 1302.pdf
Dosya Id: **some-id**
Tip: application/pdf
Dosya Link: https://docs.google.com/uc?id=**some-id**&export=download
Dosya Link: https://drive.google.com/file/d/**some-id**/view?usp=drivesdk

2 个答案:

答案 0 :(得分:3)

我终于找到了解决方案

// $client is a Google_Client object
function rootFolderId($client) {
    $service = new Google_Service_Drive($client);

    $results = $service->files->get('root');
    return $results->getId();
}

答案 1 :(得分:2)

您可以使用&#34; root&#34;作为根目录ID的别名:

$driveService->files->listFiles([
    // 'q' => '"'.MAIN_FOLDER_ID.'" in parents', // optionnal
    'q' => '"root" in parents', // optionnal
    'pageSize' => 100, // 1 to 1000
    'fields' => 'nextPageToken, files(id, name, mimeType, parents)'
]);