Dịch vụ Drive nâng cao

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

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 Google 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ác đối tượng, phương thức và tham số giống như API công khai. Để biết thêm thông tin, hãy xem phần Cách xác định chữ ký phương thức.

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

Mã mẫu

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

Tải tệp lên

Mã mẫu 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);
  }
}

Liệt kê thư mục

Mã mẫu 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 ý việc sử dụng mã thông báo trang để truy cập vào danh sách kết quả đầy đủ.

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ê 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. 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 danh sách kết quả đầy đủ.

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;
  const 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ị với tập lệnh. Để thêm thuộc tính tuỳ chỉnh vào tệp cũng hiển thị với 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 tệp tuỳ chỉnh.

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