首页 > 解决方案 > googleapis 驱动器无法访问共享驱动器文件

问题描述

我正在编写一个脚本,它应该能够按文件名搜索共享驱动器文件。

对于身份验证,我使用服务帐户。

服务帐户有权访问与我和共享驱动器共享的 Google 表格文件。

我的代码目前如下所示:

  const drive = google.drive({ version: 'v3', auth });
  const drives = await drive.drives.list();
  console.log(drives.data.drives);
  const files = await drive.files.list();
  console.log(files.data.files);

输出是:

[
  {
    kind: 'drive#drive',
    id: '0AHOBXXXXXXXX',
    name: 'Shared_drive'
  }
]
[
  {
    kind: 'drive#file',
    id: '1LAPXWyRXXXXXXXXXXXXXXXXXXXXXXX',
    name: 'Sheets File',
    mimeType: 'application/vnd.google-apps.spreadsheet'
  }
]

为什么我可以访问共享驱动器,但是当我尝试访问所有文件时,我只获得表格文件(位于共享驱动器之外)?共享驱动器包含多个目录,其中包含许多文件。为什么我看不到他们?服务帐户对共享驱动器和表格文件具有相同的查看者权限。

标签: node.jsgoogle-apigoogle-drive-api

解决方案


请看一下我从 Google 驱动器获取文件的实现。在这里,您可以找到通过分页获取文件、通过包含或排除共享文件进行过滤以及搜索功能的实现。

import { google } from 'googleapis';


const getOauth2Client = () => new google.auth.OAuth2(
  process.env.GOOGLE_DRIVE_CLIENT_ID,
  process.env.GOOGLE_DRIVE_CLIENT_SECRET,
  process.env.GOOGLE_DRIVE_REDIRECT_URL
);


export const getFiles = async ({
  tokens, pageToken, keyword, notShared
}) => {
  const oauth2Client = getOauth2Client();
  oauth2Client.setCredentials(tokens);
  const drive = google.drive({
    version: 'v3',
    auth: oauth2Client
  });
  const options = {
    pageSize: 20,
    supportsAllDrives: false,
    includeItemsFromAllDrives: false,
    orderBy: 'createdTime desc',
    spaces: 'drive',
    corpora: 'user',
    q: "mimeType contains 'image/' and trashed = false",
    fields: 'nextPageToken, files(id, webContentLink, name, webViewLink, iconLink, thumbnailLink)',
    pageToken
  };
  if (keyword) options.q += ` and name contains '${keyword}'`;
  if (notShared) options.q += " and 'me' in writers and 'me' in owners";
  const res = await drive.files.list(options);
  if (res.status !== 200) throw new Error(res.statusText);
  return res;
};

推荐阅读