שירות Drive מתקדם

שירות Drive המתקדם מאפשר לכם להשתמש ב-Google Drive API ב-Apps Script. בדומה לשירות Drive המובנה ב-Apps Script, ה-API הזה מאפשר לסקריפטים ליצור, למצוא ולשנות קבצים ותיקיות ב-Google Drive. ברוב המקרים, קל יותר להשתמש בשירות המובנה, אבל השירות המתקדם הזה מספק כמה תכונות נוספות, כולל גישה למאפיינים מותאמים אישית של קבצים וכן לגרסאות קודמות של קבצים ותיקיות.

חומרי עזר

למידע מפורט על השירות הזה, אפשר לעיין במסמכי העזר של Google Drive API. בדומה לכל השירותים המתקדמים ב-Apps Script, שירות Drive המתקדם משתמש באותם אובייקטים, שיטות ופרמטרים כמו ה-API הציבורי. מידע נוסף זמין במאמר איך נקבעים חתימות של שיטות.

כדי לדווח על בעיות ולמצוא תמיכה נוספת, אפשר לעיין במדריך לתמיכה ב-Drive API.

קוד לדוגמה

דוגמאות הקוד בקטע הזה משתמשות בגרסה 3 של ה-API.

העלאת קבצים

דוגמת הקוד הבאה מראה איך לשמור קובץ ב-Drive של משתמש.

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

הצגת רשימה של תיקיות

בדוגמת הקוד הבאה אפשר לראות איך מציגים את רשימת התיקיות ברמה העליונה ב-Drive של המשתמש. שימו לב לשימוש באסימוני דפים כדי לגשת לרשימת התוצאות המלאה.

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

הוספת מאפייני קובץ

בדוגמת הקוד הבאה נעשה שימוש בשדה 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);
  }
}