高度なドライブ サービス

高度なドライブ サービスを使用すると、Apps Script で Google Drive API を使用できます。Apps Script の組み込みのドライブ サービスと同様に、この API を使用すると、Google ドライブのファイルやフォルダを作成、検索、変更できます。ほとんどの場合、組み込みサービスのほうが使いやすいですが、この高度なサービスでは、カスタム ファイルのプロパティへのアクセス、ファイルやフォルダのリビジョンなど、いくつかの追加機能を利用できます。

Reference

このサービスについて詳しくは、Google Drive API のリファレンス ドキュメントをご覧ください。 Apps Script のすべての高度なサービスと同様に、高度なドライブ サービスでも公開 API と同じオブジェクト、メソッド、パラメータが使用されます。詳細については、メソッド シグネチャの決定方法をご覧ください。

Drive v2 サポートガイドで問題の報告やその他のサポートを確認する。

サンプルコード

以下のサンプルコードでは、バージョン 2 の API を使用しています。

ファイルのアップロード

次の例は、ユーザーのドライブにファイルを保存する方法を示しています。

Advanced/drive.gs
/**
 * Uploads a new file to the user's Drive.
 */
function uploadFile() {
  try {
    // Makes a request to fetch a URL.
    const image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();
    let file = {
      title: 'google_logo.png',
      mimeType: 'image/png'
    };
    // Insert new files to user's Drive
    file = Drive.Files.insert(file, image);
    console.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to upload file with error %s', err.message);
  }
}

フォルダの一覧表示

次の例は、ユーザーのドライブ内の最上位フォルダを一覧表示する方法を示しています。結果の完全なリストにアクセスするためにページトークンを使用しています。

Advanced/drive.gs
/**
 * Lists the top-level folders in the user's Drive.
 */
function listRootFolders() {
  const query = '"root" in parents and trashed = false and ' +
    'mimeType = "application/vnd.google-apps.folder"';
  let folders;
  let pageToken = null;
  do {
    try {
      folders = Drive.Files.list({
        q: query,
        maxResults: 100,
        pageToken: pageToken
      });
      if (!folders.items || folders.items.length === 0) {
        console.log('No folders found.');
        return;
      }
      for (let i = 0; i < folders.items.length; i++) {
        const folder = folders.items[i];
        console.log('%s (ID: %s)', folder.title, folder.id);
      }
      pageToken = folders.nextPageToken;
    } catch (err) {
      // TODO (developer) - Handle exception
      console.log('Failed with error %s', err.message);
    }
  } while (pageToken);
}

リビジョンの一覧表示

次の例は、特定のファイルのリビジョンを一覧表示する方法を示しています。リビジョンのプロパティには、特定のファイル形式でのみ使用できるものがあります。たとえば、 Google Workspace ファイルは Google ドライブの容量を消費しないため、ファイルサイズが 0 になります。

Advanced/drive.gs
/**
 * Lists the revisions of a given file. Note that some properties of revisions
 * are only available for certain file types. For example, Google Workspace
 * application files do not consume space in Google Drive and thus list a file
 * size of 0.
 * @param {string} fileId The ID of the file to list revisions for.
 */
function listRevisions(fileId) {
  try {
    const revisions = Drive.Revisions.list(fileId);
    if (!revisions.items || revisions.items.length === 0) {
      console.log('No revisions found.');
      return;
    }
    for (let i = 0; i < revisions.items.length; i++) {
      const revision = revisions.items[i];
      const date = new Date(revision.modifiedDate);
      console.log('Date: %s, File size (bytes): %s', date.toLocaleString(),
          revision.fileSize);
    }
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', err.message);
  }
}

カスタム プロパティの追加

次の例は、カスタム プロパティをファイルに追加する方法を示しています。Apps Script のドキュメント プロパティとは異なり、ドライブのカスタム ファイル プロパティには Apps Script の外部からもアクセスできます(公開設定が PUBLIC に設定されている場合)。

Advanced/drive.gs
/**
 * Adds a custom property to a file. Unlike Apps Script's DocumentProperties,
 * Drive's custom file properties can be accessed outside of Apps Script and
 * by other applications (if the visibility is set to PUBLIC).
 * @param {string} fileId The ID of the file to add the property to.
 */
function addCustomProperty(fileId) {
  try {
    const property = {
      key: 'department',
      value: 'Sales',
      visibility: 'PUBLIC'
    };
    // Adds a property to a file
    Drive.Properties.insert(property, fileId);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', err.message);
  }
}