【问题标题】:Using Google Drive API使用 Google Drive API
【发布时间】:2018-02-09 11:19:21
【问题描述】:

我正在设置将数据写入 excel 文件的数据抓取工具,然后我想将这些文件上传到我自己的驱动器帐户中的文件夹中。这将通过调度程序每天完成一次,因此完全自动化是这里的目标。

我正在查看this 快速入门指南,它经历了 Oauth2 的过程。我不想访问任何其他用户数据,只需推送我创建的文件。这可能是一个愚蠢的问题,但我是否必须通过 oAuth 流程,而不仅仅是使用 api 密钥和秘密?

在第 4 步中显示The first time you run the sample, it will prompt you to authorize access:,例如,如果它在 EC2 实例上运行,我该怎么做

谢谢

【问题讨论】:

  • 引用the docs page about authorization“您的应用程序必须使用OAuth 2.0 来授权请求​​。不支持其他授权协议”。您说您不想访问用户数据,但这就是您正在做的事情 - 它恰好是您自己的用户数据。

标签: node.js google-api google-drive-api google-api-nodejs-client


【解决方案1】:

如果您只打算访问自己的帐户,那么您应该查看service account。服务帐户已预先授权,因此您不会弹出要求访问的窗口。我不是 node.js 程序员,所以我对代码帮助不大。我没有看到用于谷歌驱动器的 node.js 的服务帐户示例,您可能能够为其他 api 之一找到一个或查看客户端库示例examples

服务帐户不是您的虚拟用户,您可以使用服务帐户电子邮件地址并与服务帐户共享您的个人 google 驱动器帐户上的文件夹或文件,并且它将具有访问权限。 read more about service accounts

【讨论】:

    【解决方案2】:

    我想我会发布我是如何让它工作的(我需要检查文件是否存在然后替换它,但那是稍后的),首先@DalmTo 和@JoeClay 有很好的观点,所以我进一步研究了它们遇到this blog post

    # index.js
    const google = require('googleapis');
    const fs = require('fs');
    const config = require('./creds.json');
    const drive = google.drive('v3');
    const targetFolderId = "123456789"
    
    
    const jwtClient = new google.auth.JWT(
      config.client_email,
      null,
      config.private_key,
      ['https://www.googleapis.com/auth/drive'],
      null
    );
    
    jwtClient.authorize((authErr) => {
      if (authErr) {
        console.log(authErr);
        return;
      }
    
    
    const fileMetadata = {
      name: './file.txt,
      parents: [targetFolderId]
    };
    
    const media = {
      mimeType: 'application/vnd.ms-excel',
      body: fs.createReadStream('./file.txt' )
    };
    
    drive.files.create({
      auth: jwtClient,
      resource: fileMetadata,
      media,
      fields: 'id'
    }, (err, file) => {
      if (err) {
        console.log(err);
        return;
      }
        console.log('Uploaded File Id: ', file.data.id);
      });
    });
    

    正如我之前所说,我的下一步是检查文件是否存在以及是否替换它

    【讨论】:

    • 您在下一行缺少尾随单引号 - 名称:'./file.txt,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多