【问题标题】:I can't see the files and folders created via code in my Google Drive我在 Google 云端硬盘中看不到通过代码创建的文件和文件夹
【发布时间】:2012-08-26 01:34:49
【问题描述】:

我是一名网络开发人员,我想从我的业务软件中访问 Google API,我已经创建了一个云端硬盘帐户 我想通过代码(VB.NET)创建一个文件夹和文件。我正在关注文档,我创建了一个 JWT(Json Web 令牌),我使用了一个服务帐户 我已经获得了一个访问令牌。

现在我想访问 Google API。 使用控制台应用程序,我创建了一些文件夹,并且可以通过代码获取已创建文件夹的列表。 但我在我的 Google Drive 帐户中看不到这些文件夹。这怎么可能?

这是我发送到服务器以显示文件夹和文件列表的请求: https://www.googleapis.com/files/{FILE_ID}?key={API_KEY}

我获得一个 JSON 字符串作为响应,其中包含与 FILE_ID 元素相关的信息。 例如:

{ “种类”:“驱动器#文件”, "id":"FILE_ID", "mimeType":"application/vnd.google-apps.folder"(如果是文件夹) / "FILE_MIMETYPE"(如果是文件), "title":"FOLDER_NAME" / "FILE_NAME", ... }

这是我用来访问 Google API 的代码:(VB.NET)

...

Public Function browseFile(ByVal fId As String) As List (Of FileSourceElement)

  Dim webclient As New WebClient()
  webclient.Headers.Add("Authorization", " Bearer " & _accessToken)
  webclient.Headers.Add("X-JavaScript-User-Agent", "Google APIs Explorer")
  Dim res As String = webclient.DownloadString("https://www.googleapis.com/drive/v2/files?key=" & _apiKey).Trim()

  'res contains the JSON with the informations of the file/folder 
  ...

End Function

Public Sub createContainer(ByVal path As String)
  Dim webclient As New WebClient()
  webclient.Headers.Add("Authorization", " Bearer " & _accessToken)
  webclient.Headers.Add("X-JavaScript-User-Agent", "Google APIs Explorer")
  webclient.Headers.Add("Content-Type", "application/json")
  webclient.UploadString("https://www.googleapis.com/drive/v2/files", _ 
                     "POST", _ 
                     "{""title"":""daEliminare2"", ""parents"":[{""id"":""" & path & """}], ""mimeType"":""application/vnd.google-apps.folder""}")
End Sub

...

在我的 Google 云端硬盘中,我没有手动创建文件夹,也没有手动上传文件,我只能通过代码完成所有操作。

正如我对您所说,我已经成功创建了一个文件夹,并且我成功打印了文件列表(通过代码),但是在我的 GDrive 中,由 UI 创建的元素 不要出现。为什么?


我在服务帐户中读到过,为了获得访问令牌,需要一个名为 Json Web Token (JWT) 的特殊 JSON 字符串,该字符串由标头组成, 声明集和签名(base64 字符串)。 字符串是:

{base64 格式的 JWT 标头}.{base64 格式的 JWT 声明集}.{base64 格式的 JWT 签名}

我的智威汤逊是:

标题

{
  "alg": "RS256",
  "typ": "JWT"
}

索赔集 { "iss": "0123456789@developer.gserviceaccount.com", // 其中 '0123456789' 是 CLIENT_ID。 “范围”:“https://www.googleapis.com/auth/drive”, "aud": "https://accounts.google.com/o/oauth2/token", "exp": timeStamp + 3600, //其中 'timeStamp' 是自 1970-01-01T00:00:00 以来的秒数。 “iat”:时间戳 }

要编写签名,我已按照本页中描述的程序进行操作:

https://developers.google.com/accounts/docs/OAuth2ServiceAccount#computingsignature

写完 JWT 后,我将它发送到服务器,并在此模式下得到一个 JSON 字符串作为响应:

{
  "access_token": "ACCESS_TOKEN", // (e.g.: 1/8xbJqaOZXS...)
  "type_token": "Bearer",
  "expire_in": 3600
}

当我获得访问令牌 (AT) 时,我使用它来访问 Google API;例如:如果我要显示所有文件和文件夹列表, 我发送的请求具有这样的标头:

授权:承载AT X-JavaScript-User-Agent:Google APIs Explorer

网址:https://www.googleapis.com/drive/v2/files?key={MY_API_KEY}

但我强调,列表中有一些项目(使用 VB.NET 控制台应用程序),而我的 Google Drive 中没有。

所以我获得了访问令牌,但我没有成功访问 Google API。

PS:我需要在不使用任何浏览器的情况下访问 Google API。

第二部分:

我在服务帐户中读到过,为了获取访问令牌,它需要一个名为 Json Web 令牌 (JWT) 的特殊 JSON 字符串,该字符串由标头组成, 声明集和签名(base64 字符串)。 字符串是:

{base64 格式的 JWT 标头}.{base64 格式的 JWT 声明集}.{base64 格式的 JWT 签名}

我的智威汤逊是:

标题

{
  "alg": "RS256",
  "typ": "JWT"
}

索赔集 { "iss": "0123456789@developer.gserviceaccount.com", // 其中 '0123456789' 是 CLIENT_ID。 “范围”:“https://www.googleapis.com/auth/drive”, "aud": "https://accounts.google.com/o/oauth2/token", "exp": timeStamp + 3600, //其中 'timeStamp' 是自 1970-01-01T00:00:00 以来的秒数。 “iat”:时间戳 }

要编写签名,我已按照本页中描述的程序进行操作:

https://developers.google.com/accounts/docs/OAuth2ServiceAccount#computingsignature

编写 JWT 后,我将其发送到服务器,并在此模式下得到一个 JSON 字符串作为响应:

{
  "access_token": "ACCESS_TOKEN", // (e.g.: 1/8xbJqaOZXS...)
  "type_token": "Bearer",
  "expire_in": 3600
}

当我获得访问令牌 (AT) 时,我使用它来访问 Google API;例如:如果我要显示所有文件和文件夹列表, 我发送的请求具有这样的标头:

授权:承载AT X-JavaScript-User-Agent:Google APIs Explorer

网址:https://www.googleapis.com/drive/v2/files?key={MY_API_KEY}

但我强调,列表中有一些项目(使用 VB.NET 控制台应用程序),而我的 Google Drive 中没有。

所以我获得了访问令牌,但我没有成功访问 Google API。

PS:我需要在不使用任何浏览器的情况下访问 Google API。

非常感谢和最好的问候

MP

【问题讨论】:

    标签: google-drive-api


    【解决方案1】:

    由于您使用的是服务帐户,所有文件夹和文件都将在此服务帐户的驱动器中创建,无法通过 Web UI 访问,并且将限制为默认配额。

    要在用户的云端硬盘中添加内容,您需要通过常规 OAuth 2.0 流程来检索该用户的凭据。您可以在此页面上找到有关 OAuth 2.0 的更多信息:

    【讨论】:

    • 答案是,您不会在 Google Drive Web UI 上看到您的应用使用服务帐户创建的任何项目,因为这些项目是代表“服务帐户”用户创建的,而不是您自己(或您正在使用的测试帐户)。
    【解决方案2】:

    如果您想在不使用 OAuth 2.0 的情况下查看用户帐户下的文件,则可以授予服务帐户编辑用户帐户下文件夹的权限。

    然后,在使用服务帐户上传文件时,请确保您将父参考 ID 设置为使用该文件夹 ID

    文件夹ID在地址栏中确定

    希望这会有所帮助。

    【讨论】:

    • 非常好的解决方案!
    【解决方案3】:

    不知道给定的解决方案。在添加文件之后,我通过添加文件权限做了不同的事情(NodeJS 代码。insertFile 在用户的经典文件上传之后调用):

    insertPermission = function(fileId, value, type, role,authClient,cb) {
      var body = {
        'value': value,
        'type': type,
        'role': role
      };
      var request = drive.permissions.insert({
        'fileId': fileId,
        'resource': body,
        'auth': authClient
      }, function (err,response) {
        cb(err,response);
      });
    }
    
    exports.insertFile = function(file,customer,callback) {
        exports.authorize(function (err,authClient) {
            drive.files.insert({
              resource: {
                title: file.name,
                mimeType: file.mimeType,
                parents: [{id:customer.googleDriveFolder}]
              },
              media: {
                mimeType: file.mimeType,
                body: file.buffer
              },
              auth: authClient
            }, function(err, response) {
              debug('error:', err, 'inserted:', response.id);
              if (!err) {
                insertPermission(response.id,customer.email,"user","writer",authClient,function (err,resp){
                  callback(null, resp);            
                });
              }
            });
        });
    };
    

    请注意,我正在使用 JWT 和私钥类型的身份验证,以及服务帐户:

    exports.authorize = function(callback) {
        if (_tokens && ((_tokens.expiry_date - (new Date()).getTime())>100 )) callback(null, _authClient);
        else {
    
        var scope = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.apps.readonly',
    'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.metadata',
    'https://www.googleapis.com/auth/drive.metadata.readonly',
    'https://www.googleapis.com/auth/drive.readonly',
    'https://www.googleapis.com/auth/drive.scripts'];
    
        var authClient = new google.auth.JWT(
                '<myServiceAccountClientId - xxx@developer.gserviceaccount.com>',
                '<path to key>.pem',
                ''); //seems we could use an user to impersonate requests, i need to test that..
        authClient.authorize(function(err, tokens) {
            if (err) {
                callback(err);
                return;
            }
            callback(null,authClient);    
        });
        }
    };
    

    【讨论】:

      【解决方案4】:

      您可以查看使用 API 上传的文件。使用以下 URL 查看您的所有文件。

      https://drive.google.com/folderview?id=XXX

      其中 XXX= 使用 API 创建的文件夹 ID。调试代码获取文件夹id,

      但是要在上面的链接中工作,您必须在创建任何文件夹或文件后提供权限,如下所示:

       Permission newPermission = new Permission();
       newPermission.Value = "youremail@gmail.com";
       newPermission.Type = "anyone";
       newPermission.Role = "reader";
       _service.Permissions.Insert(newPermission, NewDirectory.Id).Execute();
      

      查看 UI 的备用链接:https://drive.google.com/drive/folders/XXX

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-24
        • 2018-09-06
        • 1970-01-01
        相关资源
        最近更新 更多