我无法在Google云端硬盘中看到通过代码创建的文件和文件夹

时间:2012-08-31 08:46:08

标签: google-drive-api

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

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

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

我获取了一个JSON字符串作为响应,其中包含与FILE_ID元素相关的信息。 e.g:

{   “种”:“驱动器#文件”,   “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字符串,称为Json Web Token(JWT),由标题组成, 声明集和签名(base64字符串)。 字符串是:

{base64格式化JWT标头}。{base64格式化JWT claimSet}。{base64格式化JWT签名}

我的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”:timeStamp     }

要写签名,我已按照本页描述的步骤进行操作:

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 API Explorer

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

但我强调在列表中有一些项目(使用VB.NET控制台应用程序),而我的Google云端硬盘中没有任何项目。

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

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

第二部分:

我已经在服务帐户中看到,为了获得Acces Token,它需要一个特殊的JSON字符串,称为Json Web Token(JWT),由一个头部组成, 声明集和签名(base64字符串)。 字符串是:

{base64格式化JWT标头}。{base64格式化JWT claimSet}。{base64格式化JWT签名}

我的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”:timeStamp     }

要写签名,我已按照本页描述的步骤进行操作:

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

一旦我编写了JWT,我就把它发送到服务器,并在此模式下获得一个JSON字符串作为respoonse:

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

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

授权:持票人AT X-JavaScript-User-Agent:Google API Explorer

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

但我强调在列表中有一些项目(使用VB.NET控制台应用程序),而我的Google云端硬盘中没有任何项目。

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

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

非常感谢和最好的问候

MP

4 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:2)

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

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

文件夹ID在地址栏中确定

希望这有帮助。

答案 2 :(得分:0)

不知道给定的解决方案。添加文件后,添加文件权限(NodeJS代码。在用户使用经典fileUpload后调用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);    
    });
    }
};

答案 3 :(得分:0)

您可以使用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();

查看用户界面的替代链接:https://drive.google.com/drive/folders/XXX

相关问题