進階雲端硬碟服務

管理檔案和資料夾,包括自訂屬性和修訂版本。

進階雲端硬碟服務可讓您在 Google Apps Script 中使用 Google Drive API。與 Apps Script 的內建雲端硬碟服務類似,這個 API 可讓指令碼在 Google 雲端硬碟中建立、尋找及修改檔案和資料夾。在大多數情況下,內建服務較容易使用,但進階服務提供一些額外功能,包括存取自訂檔案屬性,以及檔案和資料夾的修訂版本。

這項進階服務必須先啟用才能使用

參考資料

如要進一步瞭解這項服務,請參閱 Drive API 的參考資料說明文件。與 Apps Script 中的所有進階服務一樣,進階雲端硬碟服務使用的物件、方法和參數,都與公開 API 相同。詳情請參閱「方法簽章的判斷方式」。此外,由於 delete 是 JavaScript 中的保留字,因此 Drive API 中名為 delete 的方法在進階服務 (例如 Drive.Permissions.remove()) 中會命名為 remove

如要回報問題及尋求其他支援,請參閱 Drive API 支援指南

程式碼範例

本節的程式碼範例使用 API 第 3 版

上傳檔案

以下程式碼範例說明如何將檔案儲存至使用者的 Google 雲端硬碟。

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 = {
      name: "google_logo.png",
      mimeType: "image/png",
    };
    // Create a file in the user's Drive.
    file = Drive.Files.create(file, image, { fields: "id,size" });
    console.log("ID: %s, File size (bytes): %s", file.id, file.size);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log("Failed to upload file with error %s", err.message);
  }
}

建立資料夾

以下程式碼範例說明如何在雲端硬碟中建立資料夾。

/**
 * Creates a new folder.
 */
function createFolder() {
  var folderMetadata = {
    'name': 'New Folder',
    'mimeType': 'application/vnd.google-apps.folder'
  };
  var folder = Drive.Files.create(folderMetadata);
  Logger.log('Folder ID: ' + folder.id);
}

搜尋檔案

下列程式碼範例說明如何使用查詢字串搜尋檔案。

/**
 * Searches for files with a specific name.
 */
function searchFiles() {
  var query = 'name contains "Project Plan" and trashed = false';
  var files = Drive.Files.list({
    'q': query,
    'fields': 'files(id, name, mimeType)'
  });
  if (files.files && files.files.length > 0) {
    for (var i = 0; i < files.files.length; i++) {
      var file = files.files[i];
      Logger.log('%s (ID: %s)', file.name, file.id);
    }
  } else {
    Logger.log('No files found.');
  }
}

列出資料夾

下列程式碼範例說明如何列出使用者雲端硬碟中的頂層資料夾。請注意,您可以使用網頁權杖存取完整結果清單。

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,
        pageSize: 100,
        pageToken: pageToken,
      });
      if (!folders.files || folders.files.length === 0) {
        console.log("All folders found.");
        return;
      }
      for (let i = 0; i < folders.files.length; i++) {
        const folder = folders.files[i];
        console.log("%s (ID: %s)", folder.name, folder.id);
      }
      pageToken = folders.nextPageToken;
    } catch (err) {
      // TODO (developer) - Handle exception
      console.log("Failed with error %s", err.message);
    }
  } while (pageToken);
}

列出修訂版本

以下程式碼範例說明如何列出指定檔案的修訂版本。請注意,部分檔案可能有多個修訂版本,您應使用網頁權杖存取完整結果清單。

advanced/drive.gs
/**
 * Lists the revisions of a given file.
 * @param {string} fileId The ID of the file to list revisions for.
 */
function listRevisions(fileId) {
  let revisions;
  let pageToken = null;
  do {
    try {
      revisions = Drive.Revisions.list(fileId, {
        fields: "revisions(modifiedTime,size),nextPageToken",
      });
      if (!revisions.revisions || revisions.revisions.length === 0) {
        console.log("All revisions found.");
        return;
      }
      for (let i = 0; i < revisions.revisions.length; i++) {
        const revision = revisions.revisions[i];
        const date = new Date(revision.modifiedTime);
        console.log(
          "Date: %s, File size (bytes): %s",
          date.toLocaleString(),
          revision.size,
        );
      }
      pageToken = revisions.nextPageToken;
    } catch (err) {
      // TODO (developer) - Handle exception
      console.log("Failed with error %s", err.message);
    }
  } while (pageToken);
}

新增檔案屬性

下列程式碼範例會使用 appProperties 欄位,將自訂屬性新增至檔案。自訂屬性只會顯示在指令碼中,如要將自訂屬性新增至檔案,並讓其他應用程式也能看到,請改用 properties 欄位。詳情請參閱「新增自訂檔案屬性」。

advanced/drive.gs
/**
 * Adds a custom app 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; however, appProperties are only visible to the script.
 * @param {string} fileId The ID of the file to add the app property to.
 */
function addAppProperty(fileId) {
  try {
    let file = {
      appProperties: {
        department: "Sales",
      },
    };
    // Updates a file to add an app property.
    file = Drive.Files.update(file, fileId, null, {
      fields: "id,appProperties",
    });
    console.log(
      "ID: %s, appProperties: %s",
      file.id,
      JSON.stringify(file.appProperties, null, 2),
    );
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log("Failed with error %s", err.message);
  }
}

將使用者新增至檔案

下列程式碼範例說明如何將使用者新增為檔案的編輯者,並禁止傳送電子郵件通知。

/**
 * Adds a user to a file as an editor without sending an email notification.
 */
function addEditor() {
  var fileId = '1234567890abcdefghijklmnopqrstuvwxyz';
  var userEmail = 'bob@example.com';
  var request = {
    'role': 'writer',
    'type': 'user',
    'emailAddress': userEmail
  };
  Drive.Permissions.create(request, fileId, {
    'sendNotificationEmail': false
  });
}