首页 > 解决方案 > 如何使用 Google Drive API(v3) 获取目录中所有文件的列表

问题描述

我坚持使用必须向我返回目录中所有文件列表的函数(在这种情况下,目录是“root”)。当我调用这个函数时,它会返回只有我在程序中添加的文件(这个程序也可以将文件上传到 Google Drive),而不是所有文件。它还显示了我删除的文件:/。我做错了什么?我从 Google Drive API Quickstart 复制了这个函数

service, err := getService()
    if err != nil {
        log.Fatalf("Unable to retrieve Drive client: %v", err)
    }

    r, err := service.Files.List().Q("'root' in parents").Do()
    if err != nil {
        log.Fatalf("Unable to retrieve files: %v", err)
    }
    fmt.Println("Files:")
    if len(r.Files) == 0 {
        fmt.Println("No files found.")
    } else {
        for _, i := range r.Files {
            fmt.Printf("%v (%vs )\n", i.Name, i.Id)
        }
    }

标签: gogoogle-drive-apibackupbackend

解决方案


  • 您想检索根文件夹下的所有文件。
  • 您想使用带有 golang 的 google-api-go-client 来实现此目的。
  • 您已经使用 Drive API 获取和放置 Google Drive 的值。

如果我的理解是正确的,这个答案怎么样?请认为这只是几个可能的答案之一。

问题和解决方法:

从情况来看When I call this function, it return me files that only I added with my program (this program also can upload files to Google Drive), not all files.,我认为您的范围可能包括https://www.googleapis.com/auth/drive.file. 当https://www.googleapis.com/auth/drive.file用作范围时,仅检索应用程序创建的文件。

为了检索根文件夹下的所有文件,请使用以下范围。

  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.readonly
  • https://www.googleapis.com/auth/drive.metadata.readonly
  • https://www.googleapis.com/auth/drive.metadata.

如果您只想检索文件列表,.readonly可以使用范围。

修改后的脚本:

从您的问题中,我注意到您正在使用带有 golang 和 Go Quickstart 的 google-api-go-client。在这种情况下,如何进行以下修改?

如果drive.DriveFileScope包含在范围内,请进行如下修改。

从:
config, err := google.ConfigFromJSON(b, drive.DriveFileScope)
至:
config, err := google.ConfigFromJSON(b, drive.DriveMetadataScope)

或者

config, err := google.ConfigFromJSON(b, drive.DriveReadonlyScope)
  • 如果您还想上传文件,请使用drive.DriveScope.

笔记:

  • 当您修改范围时,请删除token.json. tokFile := "token.json"请运行脚本并再次授权。这样,修改后的范围就会反映到访问令牌和刷新令牌中。请注意这一点。

参考:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。


推荐阅读