【问题标题】:Self downloading an xlsx file from google Driver从谷歌云端硬盘自行下载 xlsx 文件
【发布时间】:2019-08-16 13:01:00
【问题描述】:

所以,我正在尝试制作一个小脚本,该脚本将使用 google drive API 下载一个肯定是 excel 文件,通过遵循 google API 教程,我遇到了两个错误“无法读取未定义的属性”和“不支持请求的转换” 这是代码:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/drive'];
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  authorize(JSON.parse(content), listFiles);
});

/**
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}
/**
 * Lists the names and IDs of up to 10 files.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
  drive.files.list({
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
      console.log('Files:');
      files.map((file) => {
        console.log(`${file.name} (${file.id})`);
      });
    } else {
      console.log('No files found.');
    }
    var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
    var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
    drive.files.export({
    fileId: fileId,
    mimeType: 'xls'
    })
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);


  });

}

记住代码的第一部分只是为了授权,所以真正的问题从函数 listFiles() 开始。 感谢您的宝贵时间!

【问题讨论】:

    标签: javascript node.js google-api google-drive-api


    【解决方案1】:

    这个修改怎么样?

    修改点:

    1. 为了使用response.data,使用{responseType: 'stream'}
      • This thread 可能对您的情况有用。
      • 在线程中,使用了files.get的方法。但是这也可以用于files.export的方法。
    2. 没有xls 的mimeType。 xlsx 格式请使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 的mimeType。

    修改脚本:

    请进行如下修改。

    从:
    var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
    var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
    drive.files.export({
    fileId: fileId,
    mimeType: 'xls'
    })
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);
    
    到:
    var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
    var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
    drive.files.export({
      fileId: fileId,
      mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    }, {responseType: 'stream'}, function(err, response) {
      response.data
        .on('end', function() {
          console.log("Done.");
        })
        .on('error', function(err) {
          console.log('Error during download', err);
          return process.exit();
        })
        .pipe(dest);
    });
    

    注意:

    • 如果出现Drive API相关的错误,请再次在API控制台确认Drive API是否开启。
    • 这个修改后的脚本假设1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0的文件是Spreadsheet。

    在我的环境中,我可以确认这个修改后的脚本有效。但如果这对您的环境不起作用,我深表歉意。

    【讨论】:

    • 非常感谢你!它就像一个魅力,希望你有一个美好的一天!
    • @joao 很高兴您的问题得到了解决。也谢谢你。
    • 它对我来说也很好用。我的场景:从 API 从 google-storage 下载文件,在请求时将文件下载到用户的机器(webapp 上的按钮)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多