1

我一直在努力阅读 google-apis 的 nodejs 文档。我收集了很长的示例列表,但其中任何一个都可以帮助我做我想做的事情。我只想使用节点 js 从我的驱动器下载一个文件。

我已经设置了 OAUTH 并使用此代码获得了访问令牌(来源: http://masashi-k.blogspot.com.es/2013/07/accessing-to-my-google-drive-from-nodejs 。 html )

var googleDrive = require('google-drive');
var GoogleTokenProvider = require("refresh-token").GoogleTokenProvider,
    async = require('async'),
    request = require('request'),
    _accessToken;

var tokenProvider = new GoogleTokenProvider({
  'refresh_token': REFRESH_TOKEN,
  'client_id' : CLIENT_ID,
  'client_secret': CLIENT_SECRET
});


tokenProvider.getToken(function(err, access_token) {
  console.log("Access Token=", access_token);
  _accessToken = access_token;
});

但我不知道如何从这里继续。我尝试过这样的事情,但没有运气:

function listFiles(token, callback) {
  googleDrive(token).files().get(callback)
}

function callback(err, response, body) {
  if (err) return console.log('err', err)
  console.log('response', response)
  console.log('body', JSON.parse(body))
}

listFiles(_accessToken,callback);

我觉得我很接近,但我需要一些帮助。

提前致谢。

4

2 回答 2

2

有两种方法可以做到这一点,具体取决于您要下载的内容。下载原生 Google Doc 文件和普通文件有很大区别:

  • 必须使用files.exportAPI 方法下载文档,提供适当的 mime 类型将文档转换为
  • 可以使用files.get方法下载普通文件,如果要下载文件数据而不是元数据,请提供正确的标志

我建议使用 GoogleApis NodeJS 库(https://github.com/google/google-api-nodejs-client

初始化驱动 API:

var Google = require('googleapis');
var OAuth2 = Google.auth.OAuth2;

var oauth2Client = new OAuth2('clientId','clientSecret','redirectUrl');
oauth2Client.setCredentials({
  access_token: 'accessTokenHere'
  refresh_token: 'refreshTokenHere'
});

var drive = Google.drive({
  version: 'v3',
  auth: this.oauth2Client
});

导入文件:

drive.files.get({
  fileId: fileId,
  alt: 'media' // THIS IS IMPORTANT PART! WITHOUT THIS YOU WOULD GET ONLY METADATA
}, function(err, result) {
  console.log(result); // Binary file content here
});

导出原生 Google 文档(您必须提供 mime 类型进行转换):

drive.files.export({
  fileId: fileId,
  mimeType: 'application/pdf' // Provide mimetype of your liking from list of supported ones
}, function(err, result) {
  console.log(result); // Binary file content here
});

也许它会在这么长时间后帮助某人;)

于 2016-01-29T10:51:46.703 回答
0

在https://github.com/google/google-api-nodejs-client查看官方支持的 Google API 的 NodeJS 客户端库

从 Drive 获取文件所需的代码类似于 README 底部用于将文件插入 Google Drive 的代码。您还可以使用 API Explorer 测试 API 的参数:https ://developers.google.com/apis-explorer/#p/drive/v2/drive.files.get

这是从 Google Drive 获取文件的示例调用:

client
  .drive.files.get({ fileId: 'xxxx' })
  .execute(function(err, file) {
  // do something with file here
});
于 2014-05-21T05:47:14.403 回答