【问题标题】:What is correct syntax of retrieving next page in google drive API through nextPageToken通过 nextPageToken 在 google drive API 中检索下一页的正确语法是什么
【发布时间】:2021-03-23 18:03:14
【问题描述】:

我正在开发一个应用程序,该应用程序通过向 nodeJs API 发出请求来列出谷歌驱动器的文件,以获取驱动器中存在的所有文件,我需要通过此 API 请求另一组文件,但我不知道找出使用从以前的drive.files.list({}) 收到的 nextPageToken 请求下一页文件的正确方法。我在文档中进行了搜索,但找不到有关此用例的任何示例。 下面是我正在使用的代码,但这段代码只是一次又一次地返回相同的 10 个文件。

..other code here..
drive.files.list({
    orderBy: 'name',
    q: "", 
    nextPageToken:req.body.pageToken, // req.body.pageToken is nextPageToken got in previous requests 
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
}, (err, resp) => {
..other code here..

【问题讨论】:

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


    【解决方案1】:

    我相信你的目标和情况如下。

    • 您希望使用 googleapis for Node.js 将所有文件作为您的 Google Drive 列表检索。
    • 您已经能够使用 Drive API 检索文件列表。
      • 您的drive 可用于从您的 Google 云端硬盘中检索文件列表。

    修改点:

    • nextPageTokenpageToken
    • pageSize 最大为 1000。这种情况下,使用 1000 时,可以减少 Drive API 的使用次数。
    • 为了使用nextPageToken,在这个答案中,我建议使用do while循环。

    当你的脚本被修改后,变成如下。

    修改脚本:

    async function main(auth) {
      const drive = google.drive({ version: "v3", auth });
    
      const fileList = [];
      let NextPageToken = "";
      do {
        const params = {
          // q: "",  // In this case, this is not required.
          orderBy: "name",
          pageToken: NextPageToken || "",
          pageSize: 1000,
          fields: "nextPageToken, files(id, name)",
        };
        const res = await drive.files.list(params);
        Array.prototype.push.apply(fileList, res.data.files);
        NextPageToken = res.data.nextPageToken;
      } while (NextPageToken);
    
      console.log(fileList.length);  // You can see the number of files here.
    }
    
    • drive.files.list 返回承诺。所以你可以使用上面的脚本。

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多