Dịch vụ Drive nâng cao

để quản lý tệp và thư mục, bao gồm cả các thuộc tính tuỳ chỉnh và bản sửa đổi.

Dịch vụ Drive nâng cao cho phép bạn sử dụng API Google Drive trong Google Apps Script. Tương tự như dịch vụ Drive tích hợp của Apps Script, API này cho phép các tập lệnh tạo, tìm và sửa đổi tệp cũng như thư mục trong Google Drive. Trong hầu hết các trường hợp, dịch vụ tích hợp dễ sử dụng hơn, nhưng dịch vụ nâng cao này cung cấp một số tính năng bổ sung, bao gồm cả quyền truy cập vào các thuộc tính tuỳ chỉnh của tệp cũng như các bản sửa đổi cho tệp và thư mục.

Đây là một dịch vụ nâng cao mà bạn phải bật trước khi sử dụng.

Tài liệu tham khảo

Để biết thông tin chi tiết về dịch vụ này, hãy xem tài liệu tham khảo về API Drive. Giống như tất cả các dịch vụ nâng cao trong Apps Script, dịch vụ Drive nâng cao sử dụng cùng các đối tượng, phương thức và tham số như API công khai. Để biết thêm thông tin, hãy xem bài viết Cách xác định chữ ký phương thức. Ngoài ra, các phương thức có tên delete trong API Drive được đặt tên là remove trong dịch vụ nâng cao (chẳng hạn như Drive.Permissions.remove()), vì delete là một từ dành riêng trong JavaScript.

Để báo cáo vấn đề và tìm các hình thức hỗ trợ khác, hãy xem hướng dẫn hỗ trợ API Drive.

Mã mẫu

Các mẫu mã trong phần này sử dụng API phiên bản 3.

Tải tệp lên

Mẫu mã sau đây cho biết cách lưu tệp vào Drive của người dùng.

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);
  }
}

Tạo thư mục

Mẫu mã sau đây cho biết cách tạo thư mục trong Drive.

/**
 * 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);
}

Tìm tệp

Mã mẫu sau đây cho biết cách tìm tệp bằng chuỗi truy vấn.

/**
 * 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.');
  }
}

Liệt kê thư mục

Mẫu mã sau đây cho biết cách liệt kê các thư mục cấp cao nhất trong Drive của người dùng. Lưu ý về việc sử dụng mã thông báo trang để truy cập vào danh sách đầy đủ các kết quả.

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);
}

Liệt kê các bản sửa đổi

Mã mẫu sau đây cho biết cách liệt kê các bản sửa đổi cho một tệp nhất định. Xin lưu ý rằng một số tệp có thể có nhiều bản sửa đổi và bạn nên sử dụng mã thông báo trang để truy cập vào danh sách đầy đủ các kết quả.

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);
}

Thêm thuộc tính tệp

Mã mẫu sau đây sử dụng trường appProperties để thêm thuộc tính tuỳ chỉnh vào tệp. Thuộc tính tuỳ chỉnh chỉ hiển thị cho tập lệnh. Để thêm thuộc tính tuỳ chỉnh vào tệp cũng hiển thị cho các ứng dụng khác, hãy sử dụng trường properties. Để biết thêm thông tin, hãy xem bài viết Thêm thuộc tính tuỳ chỉnh của tệp.

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);
  }
}

Thêm người dùng vào tệp

Mã mẫu sau đây cho biết cách thêm người dùng làm người chỉnh sửa vào tệp và ngăn thông báo qua email.

/**
 * 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
  });
}