【问题标题】:Nodejs - Unable to fetch data of files from google driveNodejs - 无法从谷歌驱动器获取文件数据
【发布时间】:2022-01-07 23:15:56
【问题描述】:

我正在尝试从谷歌驱动器获取文件数据。 为此,我已经完成了https://developers.google.com/drive/api/v3/quickstart/nodejs

中提到的所有步骤

我还可以获取驱动器中的文件列表。但我不明白如何获取文件中的数据。我已经尝试了在谷歌中找到的以下代码,但我得到的响应为undefined

这是我的代码

    const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const zlib = require("zlib");
const creds = require("../../../credentials.json")
const getfilelist = require("google-drive-getfilelist");
module.exports = async (req, res) => {
    try {
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.

  authorize(creds, listFiles);

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

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @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);
      // Store the token to disk for later program executions
      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 topFolderId = "1MTER3d8AVkpw0-_32xpxzZtyuP8iMH66"; // Please set the top folder ID.
getfilelist.GetFileList(
  {
    auth: auth,
    fields: "files(*)",
    id: topFolderId,
  },
  (err, res) => {
    if (err) {
      console.log(err);
      return;
    }
    const fileList = res.fileList.flatMap(({ files }) => files);
    fileList.map((file) => {
      console.log('iiiiii',file)
      downloadFile(auth, file.id)
    });
  }
);
}

function downloadFile(auth, fileId) {const drive = google.drive({version: 'v3', auth});
console.log('fileIdfileId',fileId)
let progress = 0;
drive.files.get({
  fileId: fileId,
  alt: 'media'
},
function(err, { data }) {
  console.log('actual data', data);
  var bdata = Buffer.from(data, 'utf8')
  console.log('buffered data', bdata)
})




}
} catch (error) {
    console.log(error);
}
};

在代码 console.log('actual data',bdata) 附近,我得到的输出类似于PK"♠�S↕word/numbering.xml��MN�0►�O�↔"��$§ ¶5� 6�♥���X�=��I��q��R$��U��������Kɠ�h♣��ˈ♦\3Ȅ.R���x"�uTgT��)9rK���u��J�9�}�Gh�(���9���e%W�.�p�9���/§�Ce▬♀��N�¶�↑���t↑HI�:�►♂%↑��ܝ$ ���� ��Jv�*ŵ;;�����☺�-��=Mͥ�b�C�♫Q+��k�¶�♀i��dk�f♠�qk��][∟�q4a� 'Ġ���OϾ‼E�▲0�t\�♠���vF�↓ga�F�қ�#����.�y^ꍘ��+�W� PI‼C⌂h☺=♣PK"♠�S◄word/settings.xml���n�0♀ǟ�►���I6↑uzX�����=#ɶ►}A����'ǖդ@�f�H⌂�?�♀M?>�§|q��2%K��R��↕+�d]�?�?����:�♦���Dgj����cWX���♂O��►�D�s�H↕�����♦8⌂5u"�∟[��Jhp��8s�$O�-→1�D��ňX

在 console.log('buffered data', bdata) 附近,我得到的输出为<Buffer 50 4b 03 04 14 00 08 08 08 00 22 06 ef bf bd 53 00 00 00 00 00 00 00 00 00 00 00 00 12 00 00 00 77 6f 72 64 2f 6e 75 6d 62 65 72 69 6e 67 2e 78 6d 6c ... 15880 more bytes>

如何从文件中获取实际文本。

有人可以帮忙

【问题讨论】:

  • 如果你删除第三个参数中的回调,并在第一个.on 上记录响应,你会得到什么吗?
  • 它已经是你的代码的一部分,你将它下载到 sample.txt var dest = fs.createWriteStream('./sample.txt'); 你说的是那个示例。 txt 为空?
  • @DaImTo 是的,它是空的
  • @Iamblichus 第三个参数?能具体点吗
  • 嗨,this answer 对您有用吗?如果是这种情况,请考虑接受stackoverflow.com/help/someone-answers

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


【解决方案1】:

尝试遵循documentation中的代码

function downloadFile(auth, fileId) {
    const drive = google.drive({
        version: 'v3',
        auth
    });
    var dest = fs.createWriteStream('./sample.txt');
    drive.files.get({
            fileId: fileId,
            alt: 'media'
        })
        .on('end', function() {
            console.log('Done');
        })
        .on('error', function(err) {
            console.log('Error during download', err);
        })
        .pipe(dest);
}

【讨论】:

  • @DalmTo 我收到错误为 TypeError: drive.files.get(...).on is not a function
  • 您现有的代码使用 drive.files.get 这意味着您将其放置在错误的位置。
  • @DalmTo 我在哪里做错了?代码应该放在哪里?
  • 用这个方法替换你的downloadFile,然后试试。
  • @DalmTo 我替换了你的代码。更换时出现错误 TypeError: drive.files.get(...).on
【解决方案2】:

问题:

您正在使用drive.metadata.readonly 范围授权应用程序,这不会让您访问文件内容,也不会让您下载它。

解决办法:

删除您生成的token.json,修改代码中的SCOPES,使用drive 等适当的范围,然后再次通过授权:

const SCOPES = ['https://www.googleapis.com/auth/drive'];

参考:

【讨论】:

  • 这非常接近。我能够获取列表,但出现 403 错误。代码:403,错误:[ { 域:'global',原因:'fileNotExportable',消息:'导出仅支持文档编辑器文件。' } ] } 。我还对我的代码进行了更改并在我的问题中发布了新代码
  • @Saisri 您收到此错误正是由于您对代码所做的更改。正如您收到的错误所说,files.export 用于下载 Google Docs 文件(请参阅Download a Google Workspace Document)。对于常规文件,您必须使用files.get(请参阅Download a file stored on Google Drive)。因此,回滚这些更改并使用您最初使用的 files.get
  • 我正在获取以下格式的数据。如何转换为文本格式 ♥���X�=��I��q��R$��U��������Kɠ�h♣��ˈ♦\3Ȅ.R�� �x"�uTgT��)9rK���u��J�9�}�Gh�(����9���e%W�.�p�9���/§�Ce▬♀� „N�¶�↑���t↑HI�:�►♂%↑��� C�♫Q+��k�¶�♀i��dk�f♠�qk��][∟�q4a�'Ġ���OϾ‼E�▲0�t\�♠����vF�↓ ga�F�қ�#���.�y^ꍘ��+�W�
  • @Saisri 如果您只想检索文本内容,并且不想实际下载文件,只需从files.get 中删除第二个参数:{responseType: 'stream'}(因为您编辑了您的代码这么多次,我不确定你是否已经这样做了)。
  • 对不起,我现在这样做了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
相关资源
最近更新 更多